简体   繁体   English

如何将actionlistener添加到整个类而不将其单独分配给各个组件?

[英]How to add actionlistener to whole class without assigning it to components individually?

For example, lets say I have 5 JButtons 例如,假设我有5个JButton

b1 = new JButton("Add");
b2 = new JButton("Add 2");
b3 = new JButton("Find Connection");
b4 = new JButton("Read File");
b5 = new JButton("Exit");

If I want to add Actionlistener to all 5 buttons, I'd have to do this 5 times for each button. 如果要向所有5个按钮添加Actionlistener,则必须为每个按钮执行5次此操作。

b1.addActionListener(this);

Is there a way to add actionlistener to all JButtons in the class in one line of code? 有没有一种方法可以在一行代码中向类中的所有JButton添加actionlistener? Or even better add actionlistener to every component in the class? 甚至更好地向类中的每个组件添加actionlistener?

You could make a loop that adds the listener to the buttons. 您可以创建一个将侦听器添加到按钮的循环。

    for(int i=0; i<5; i++)
{
    button[i].addActionListener(new ButtonListener());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM