如何确定ActionListener中的事件源? [英] How to determine the event source in an ActionListener?
问题描述
好的。我不确定问题的标题以及是否使用了正确的词。
因为我是一个自学成才的业余爱好者,所以我很难问我的问题,因为我不知道正确的事物用语,所以我会用代码写一些东西然后问我的问题。我编写时没有导入语句,没有设置布局和滚动条以及其他一些东西,只是为了使其更简单。
Ok. I'm not sure about the title of my question and whether I used the right words. As I am a self taught total amateur I'm finding it hard to ask my question as I don't know the correct terms for things so I will write something in code and then ask my question. I've written it without import statements, setting up layouts and scrollbars and some other things just to keep it simpler.
public class Foo{
JTextArea text;
public static void main(String[] args){
Foo foo = new Foo;
foo.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
JPanel panel = new JPanel();
frame.setVisible(true);
frame.setSize(600, 300);
frame.getContentPane().add(BorderLayout.EAST, panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(button2);
text = new JTextArea(10, 20);
panel.add(text);
button.addActionListener(new ButtLis());
button2.addActionListener(new ButtLis());
}
class ButtLis implements ActionListener{
@override
// this is where I have the problem
text.append();
}
}
我想要的是一个if语句进入我的内部类(ButtLis),它将确定按下了哪些按钮,然后基于该按钮将某些文本附加到JTextArea。但我不知道该如何呼叫才能找出按下了哪个按钮。
What I want is an if statement to go into my inner class (ButtLis) which will determine which of the buttons are pressed and then append certain text to the JTextArea based on that. But I don't know what to call to find out which button was pressed.
推荐答案
您有两种选择。在当前情况下, JButton
对象在构造函数中位于本地范围内,则需要检查 actionCommmand
,因为无法从 ActionListener
使用其当前作用域访问这些对象。因此,您可以这样做
You have a couple options. In the current case you have, where the JButton
objects are locally scoped within the constructor, you would need to check for actionCommmand
because the objects are not accessible from the ActionListener
with their current scope. So you could do this
class ButtLis implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("One".equals(command)) {
// do something
}
}
}
如果要比较对象源,则需要为按钮提供全局作用域
If you wanted to compare object source, you would need to give your buttons a global scope
public class Foo {
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
class ButtLis implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
}
}
}
}
第三种选择是分别注册按钮
A third option is to register the buttons individually
public void go() {
...
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
}
这篇关于如何确定ActionListener中的事件源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!