简体   繁体   English

我可以将ActionListener添加到JPanel

[英]Can I add an ActionListener to a JPanel

I am creating a swing program which basically has a lot of buttons, and I was thinking that instead of adding the listener individually to each button, if I could add the listener to the JPanel instead, and read the events using .getSource() function, things would be a whole lot easier? 我正在创建一个基本上有很多按钮的swing程序,我想的是,不是将监听器单独添加到每个按钮,如果我可以将监听器添加到JPanel ,并使用.getSource()函数读取事件,事情会变得容易多少? Is it possible? 可能吗?

Adding a listener to a component doesn't mean that you are also adding that listener to the internal components. 向组件添加侦听器并不意味着您还要将侦听器添加到内部组件。 Instead, think of using groups of buttons (eg a button array) and add the listener to all buttons with one iteration. 相反,考虑使用按钮组(例如按钮数组)并通过一次迭代将监听器添加到所有按钮。

for(JButton button : buttonsArray)
    button.addActionListener(yourActionListener);

I am creating a swing program which basically has a lot of buttons, and I was thinking that instead of adding the listener individually to each button, if I could add the listener to the JPanel instead, and read the events using .getSource() function, things would be a whole lot easier? 我正在创建一个基本上有很多按钮的swing程序,我想的是,不是将监听器单独添加到每个按钮,如果我可以将监听器添加到JPanel,并使用.getSource()函数读取事件,事情会变得容易多少? Is it possible? 可能吗?

not possible to add ActionListener , only MouseListener can do that, but not correct way for JButton 不可能添加ActionListener ,只有MouseListener可以这样做,但JButton方法不正确

depends of your code, you have to add ActionListener to every JButtons and to determinte which one is pressed by 取决于你的代码,你必须将ActionListener添加到每个JButton并确定按下哪个

  • put/getClientProperty

  • ActionCommand

  • programatically loop instide arrays of JButtons and to compare event and JButton 以编程方式循环灌注JButtons数组并比较事件和JButton

No, you can not, take a look on documentation 不,你不能,看看文档

If all your buttons have the same listener behavior, add them to ArrayList<JButton> and in loop add the same instance of ActionListener 如果所有按钮都具有相同的侦听器行为,请将它们添加到ArrayList<JButton>并在循环中添加相同的ActionListener实例

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

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