如何在Java中将ActionListener添加到JButton中

use*_*037 27 java user-interface swing jbutton actionlistener

private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
Run Code Online (Sandbox Code Playgroud)

如何将动作侦听器添加到这些按钮,以便从我可以调用actionperformed它们的主方法,所以当它们被单击时,我可以在我的程序中调用它们?

Dav*_*lle 52

两种方式:

1.在你的类中实现ActionListener,然后使用jBtnSelection.addActionListener(this); Later,你必须定义一个menthod , public void actionPerformed(ActionEvent e). 但是,对多个按钮执行此操作可能会造成混淆,因为该actionPerformed方法必须检查每个事件的来源(e.getSource())以查看它来自哪个按钮.

2.使用匿名内部类:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );
Run Code Online (Sandbox Code Playgroud)

之后,你必须定义selectionButtonPressed().当您有多个按钮时,这会更好用,因为您对处理操作的各个方法的调用就在按钮的定义旁边.

第二种方法还允许您直接调用选择方法.在这种情况下,你也可以调用selectionButtonPressed()一些其他的动作 - 比如,当一个计时器熄灭或什么时候(但在这种情况下,你的方法会被命名为不同的东西,也许selectionChanged()).


Ale*_*x B 7

最好的办法是查看Java Swing教程,特别是关于Buttons教程.

简短的代码片段是:

jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
Run Code Online (Sandbox Code Playgroud)