Hi, I am trying to add an event handling feature to an old program I wrote.
Here is the relevant code:
public class CalculatorLayout extends JFrame{
private BorderLayout layout;//layout object. Do I need a flowlayout at all?
private JPanel numberKeysPanel;//contains the number keys panel
//private JPanel calculationAreaPanel;//contains the calculation panel
private GridLayout numberKeysGrid;//contains the number keys
private JTextField calculationArea;//text field where numbers are displayed
private JButton numberKey;//symbols
private String[] labels;//hold the labels
public CalculatorLayout(){
super( "Calculator" );
layout = new BorderLayout( 0, 5 );//create FlowLayout. Do I need a flowlayout at all?
setLayout( layout );
calculationArea = new JTextField( "", 30 );//created empty display
numberKeysPanel = new JPanel();
String[] labels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
numberKeysGrid = new GridLayout( 4, 4, 5, 5 );//create grid layout
for( int counter = 0; counter < labels.length; counter++ ){
numberKey = new JButton( labels[ counter ] );//create button with apppropriate label
numberKeysPanel.add( numberKey );//add buttons to panel
}//end of loop
numberKeysPanel.setLayout( numberKeysGrid );//attach grid layout to jpanel
//set up GridLayout manager
//numberKeysPanel.add( numberKeysGrid );//add grid to jpanel
add( calculationArea, BorderLayout.PAGE_START );//add calc area txt field to jframe
add( numberKeysPanel, BorderLayout.CENTER );//add jpanel to the jframe
}//end of constructor
Now, I was just adding the even handling code, but I was wondering, since the buttons are created in a loop there is no way that I can use .addActionListener
to each button unless I do that in a for loop, correct? So something like this I presume:
//FOR EVENT HANDLING
ButtonHandler handler = new ButtonHandler();
for(int counter = 0; counter < labels.length; counter++){
numberKey.addActionListener(handler);
}
Thanks