如果我用名称声明JButton,我知道可以将ActionListener添加到JButton。
JButton showDialogButton = new JButton("Click Me");
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// display/center the jdialog when the button is pressed
JDialog d = new JDialog(frame, "Hello", true);
d.setLocationRelativeTo(frame);
d.setVisible(true);
}
});
但是如果我有以下代码,该怎么办:
MyJFrame frame = new MyJFrame();
frame.setSize(500,300);
JPanel base = new JPanel();
base.setLayout(new BorderLayout());
JPanel north = new JPanel();
north.add(new JLabel("Name"));
north.add(new JTextField());
north.add(new JButton("Enter"));
north.add(new JButton("Exit"));
我将不胜感激。
在添加项之外进行声明
JButton exit = new JButton("exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//do stuff
}
});
north.add(exit);
然后对要添加侦听器的所有其他组件执行相同的操作
为了将ActionListener
添加到JButton
,您将必须保留对其的引用,因此,您不能仅将其作为new
传递给JPanel
的构造函数。解决方案实质上是在做您之前所做的事情,即分别声明并初始化它们:JButton myButton = new JButton("My Button");
,然后像之前一样将ActionListener
添加到您的JPanel
:
myButton.addActionListener(new ActionListener() ...);
然后就是north.add(myButton);
。
更新:
将ActionListener添加到匿名对象的更好的方法可以通过使用here指出的双括号初始化语法来完成。这是一个例子:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GuiTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 300);
JPanel base = new JPanel();
base.setLayout(new BorderLayout());
JPanel north = new JPanel();
Component comp1 = north.add(new JLabel("Name"));
System.out.println("comp1 class type: " + comp1.getClass().getName());
Component comp2 = north.add(new JTextField());
System.out.println("comp2 class type: " + comp2.getClass().getName());
Component comp3 = north.add(new JButton("Enter"));
System.out.println("comp3 class type: " + comp3.getClass().getName());
north.add(new JButton("Exit") {{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("EXIT");
}
});
}});
base.add(north);
frame.getContentPane().add(base);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
在搜索Java API之后,我发现add
方法返回了要添加的组件。不幸的是,它只是一个普通的add
对象,如果没有强制转换就无法链接。但是您可以像这样获得添加的对象:
Component
此代码完整且可验证(我在Arch Linux x64计算机上对其进行了测试)。这有点丑陋,但有效。