2011-04-07 90 views
1

我希望当我输入一个按钮时,文本出现在控制台中。我怎么能结合我的混淆的方法,有人可以解释和举例。java swing事件

+1

你为什么不看教程?答案在每本书和Swing教程中都很基本,很容易找到。 – 2011-04-07 12:44:22

回答

1

尝试

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 
+0

tnx到所有,现在我明白了与它们合作的主要方式:) – weardstuff 2011-04-07 12:49:55

+0

请注意,在控制台上打印任何用于用户的GUI是'非常'的。为什么不用一个按钮和一个'JTextField'或'JTextArea'将输出写入? – 2011-04-07 13:24:16

0

使用的MouseListener。例如:

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

MouseAdapter是具有默认的所有的MouseListener的提供其他方法的空实现一个特殊的MouseListener,所以你不必重写它们。您可能想要查看适用于MouseAdapter,MouseListener和MouseEvent的Javadoc。

+0

啊,我误解了你的问题 - 我假设你想知道光标是否进入了按钮。如果你想知道按钮是否被点击过,那么Bala R的解决方案就是要走的路。 – 2011-04-07 12:41:53

0

将一个ActionListener添加到按钮。在actionPerformed()方法在控制台上打印文本或任何你想要的。