I've got a simple java swing code where a text field changes when the button is hovered over and clicked, but when i use a variable to deactivate the mouseExited event, it does not work and continues to change the text field. I think its to do with the variable only being available to the mouseClicked event? How would i fix this. Thanks
my imports are java.awt and javax.swing
public static void main(String[] args) {
boolean check = true;
JFrame f =new JFrame("ActionListener Example");
JTextField tf = new JTextField("You should press button 1");
tf.setBounds(100,100, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
tf.setText("you did it");
boolean check = false;
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
tf.setText("DO IT!");
}
@Override
public void mouseExited(MouseEvent e) {
if (check) {
tf.setText("You should press the button");
}
}});
f.setLayout(new FlowLayout());
f.setSize(400,400);
f.add(b);
f.add(tf);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
I think its to do with the variable only being available to the mouseClicked event? How would i fix this.
Then don't define a second "check" variable in the mouseClicked method.
//boolean check = false;
check = false;
Edit:
Local variable check defined in an enclosing scope must be final or effectively final
Start be rewriting your entire class to give it a better structure.
Read the section from the Swing tutorial on How to Use Buttons.... Download the ButtonDemo
code and modify it.
The demo code will show you how to structure your code so that