Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

java - How To use MouseClicked event to prevent mouseExited event?

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  1. all the code is NOT contained in the main() method:
  2. you use layout managers
  3. you create the GUI on the Event Dispatch Thread (EDT)
  4. your class can use "instance" variables, instead of a local variable. You "check" variable will be an instance variable.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...