In the previous posts we have seen how to put a button on a JFrame. Today we will see how to put two buttons on a frame . This could be easily done . But how to get action events for two different buttons when each button needs to do something different ?
POSSIBLE OPTIONS :
(1) Implement two actionPerformed() methods
class MyGui implements ActionListener{
// coding goes here
public void actionPerformed(ActionEvent event){
frame.repaint ( ) ;
}
public void actionPerformed(ActionEvent event){
label.setText("Hello !!") ;
}
}
There's flaw in it !! We can't do this. The same method cannot be implemented twice in a Java class.It will not compile and secondly, how would the event source (button) know which of the methods to call.
(2) Creating two separate ActionListener classes
class MyGui {
JFrame frame ;
Jlabel label ;
void gui ( ) {
// code to instantiate the two listeners and register one with the color button
// and the other with label button .
}
}
class ColorButtonListener implements ActionListener {
public static void main ( String args [ ] ){
frame.repaint() ;
}
}
class LabelButtonListener implements ActionListener {
public static void main ( String args [ ] ){
label.setText("Hello !!") ;
}
}
These classes won't have access to the variables they need to act on 'frame' and 'label' .
SOLUTION : INNER CLASS :
Simple inner class :
class MyOuterClass {
private int x ;
class MyInnerClass {
void go( ){
x = 42 ; // uses 'x' as if it were a variable of the inner class
}
}
}
An inner class gets access to use the outer class's variables and methods even if they are private. We will be continuing with the example which we used in the last post.
OUTPUT :
WHEN WE CLICK THE CHANGE COLOR BUTTON THE COLOR CHANGES !!
WHEN WE CLICK THE CHANGE LABEL BUTTON THE LABEL ON THE LEFT SIDE CHANGES ALONG WITH THE CHANGE IN CIRCLE COLOR (this is because the circle changes color every time a button gets clicked)
No comments:
Post a Comment