简体   繁体   English

Java Swing事件

[英]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. 使用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. MouseAdapter是一种特殊的MouseListener,具有MouseListener提供的所有其他方法的默认空实现,因此您不必重写它们。 You may want to look at the Javadoc for MouseAdapter, MouseListener, and MouseEvent. 您可能需要查看适用于MouseAdapter,MouseListener和MouseEvent的Javadoc。

Add an ActionListener to the button. ActionListener添加到按钮。 In the actionPerformed() method print text on the console or whatever else you want. actionPerformed()方法中,在控制台或您想要的其他任何位置上打印文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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