我已经创建并向 JDialog 添加了一个按钮,如下所示:
JDialog dialog = new JDialog();
dialog.setLayout(new GridLayout(6, 1));
dialog.add(new JButton("test"));
这会添加按钮 JDialog。但我是否可以向其中添加 ActionListener
?
我知道如果我创建一个全新的按钮本身是可能的,例如:
JButton button = new JButton("test");
button.addActionListener....
dialog.add(button);
但我想知道如果没有这个我是否可以做。
到目前为止,我已经达到了 dialog.getRootPane().getContentPane().getComponent(1)
的目的,但卡在这里,不知道如何实现 actionListener。任何帮助将不胜感激。
最佳答案
我认为没有办法在初始化 JButton 时添加监听器。
初始化按钮并添加监听器将按照您所说的进行。
另一种方式,您可以使用实用程序方法来创建带有监听器的 JButton,如下所示。
dialog.add(getButton("Test", new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Action Logic
}
}));
private JButton getButton(String name, ActionListener listener) {
JButton button = new JButton(name);
button.addActionListener(listener);
return button;
}
关于java - 将操作添加到 JDialog 中动态创建的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31698431/