在Java Swing中,我可以将侦听器注册到某个gui事件,如下所示
guiElement.addMouseListener(myListener);
Run Code Online (Sandbox Code Playgroud)
但是如果我想在我的GUI应用程序中自动注册到所有鼠标事件呢?
我应该将myListener注册到每个元素吗?
换句话说,我正在寻找的是类似的东西
myListener.registerToEventType(MouseEvent.class)
Run Code Online (Sandbox Code Playgroud)
任何的想法?
谢谢
我认为你不能按照你想要的方式那样做。一种可能的方法是使用Action Commands,如本答案中所述。
JButton hello = new JButton("Hello");
hello.setActionCommand(Actions.HELLO.name());
hello.addActionListener(instance);
frame.add(hello);
JButton goodbye = new JButton("Goodbye");
goodbye.setActionCommand(Actions.GOODBYE.name());
goodbye.addActionListener(instance);
frame.add(goodbye);
...
}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand() == Actions.HELLO.name()) {
JOptionPane.showMessageDialog(null, "Hello");
}
else if (evt.getActionCommand() == Actions.GOODBYE.name()) {
JOptionPane.showMessageDialog(null, "Goodbye");
}
}
Run Code Online (Sandbox Code Playgroud)
这只是一个例子,但你已经明白了。
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |