简体   繁体   中英

java swing events

I want when I enter a button, text to appear in the console. How can I combine the methods there is my comfusing, can someone explain and give example.

Try

    JButton button = new JButton("Button1");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
        System.out.println("Button1 was Clicked!");

        }
    });

    // add button to a container

Use a MouseListener. For example:

JComponent button = new JButton();
component.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.println("Mouse entered the button");
    }
});

MouseAdapter is a special MouseListener that has default empty implementations of all the other methods that the MouseListener provides, so you don't have to override them. You may want to look at the Javadoc for MouseAdapter, MouseListener, and MouseEvent.

Add an ActionListener to the button. In the actionPerformed() method print text on the console or whatever else you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM