Reputation: 321
I just made my first event based GUI in java, but i don't understand where i am wrong. the code worked fine when there was no event handling applied..
Here's the code.
package javaapplication1;
import javax.swing.*;
import java.awt.event.*;
class Elem implements ActionListener{
void perform(){
JFrame frame = new JFrame();
JButton button;
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent ev){
button.setText("Clicked");
}
}
public class JavaApplication1 {
public static void main(String[] args) {
Elem obj = new Elem();
obj.perform();
}
}
Upvotes: 3
Views: 135
Reputation: 5538
There is a problem with variable scope. Move the JButton button;
definition outside of the perform()
method so that actionPerformed()
can access it.
JButton button;
void perform(){
JFrame frame = new JFrame();
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
When you define an object inside of a method (e.g. perform()
), its scope is limited to that method (inside the curly braces). This means that other methods inside your class cannot access that variable.
By moving the object definition outside of the method, it now has class level scope. This means that any method within that class can access the variable. You're still defining its value inside of perform()
, but now it can be accessed by other methods, including actionPerformed()
.
See here for more explanation.
Upvotes: 2
Reputation: 21961
As you used button
object inside actionPerformed
method. So declare button
globally.
class Elem implements ActionListener{
JButton button;// Declare JButton here.
void perform(){
JFrame frame = new JFrame();
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent ev){
button.setText("Clicked");
}
}
public class JavaApplication1 {
public static void main(String[] args) {
Elem obj = new Elem();
obj.perform();
}
}
Upvotes: 2