java中事件源是指什么时候_java-如何确定ActionListener中的事件源?

好.我不确定问题的标题以及是否使用正确的词.

因为我是一个自学成才的业余爱好者,所以我很难问我的问题,因为我不知道事物的正确术语,因此我将用代码编写一些东西然后问我的问题.我编写时没有导入语句,没有设置布局和滚动条以及其他一些东西,只是为了使其更简单.

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.但我不知道该如何呼叫才能找出按下了哪个按钮.

解决方法:

您有两种选择.在当前情况下,JButton对象在构造函数中位于本地范围内,您将需要检查actionCommmand,因为无法使用当前范围从ActionListener访问这些对象.所以你可以这样做

class ButtLis implements ActionListener{

@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if ("One".equals(command)) {

// do something

}

}

}

如果要比较对象源,则需要给按钮一个全局范围

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) {

}

}

}

}

第三种选择是分别注册按钮

public void go() {

...

button.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

// do something

}

});

}

标签:actionlistener,swing,jbutton,java

来源: https://codeday.me/bug/20191122/2056469.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值