Java:处理单独 JPanel 组件内组件上的事件

发布于 2024-09-14 04:11:58 字数 107 浏览 1 评论 0原文

所以我有一个 JFrame,我添加了一个自定义 JPanel 组件。

JPanel 组件有一个按钮,我想在 JFrame 中将侦听器附加到该按钮。

最好的方法是什么?

So I have a JFrame which I've added a custom JPanel component.

The JPanel component has a button that I want to attach a listener to in my JFrame.

What is the best way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲娇萝莉攻 2024-09-21 04:11:58

除非我读错了,否则当您自己添加 JPanel 时,您只需向按钮添加一个动作监听器即可。

JButton.addActionListener(... some listener);

或者您在这里问的是其他事情吗?例如,如果自定义 JPanel 不是由您开发的。然后在这种情况下,查看面板是否公开 API 来向其按钮添加侦听器,如果没有,那么最后一个选项是迭代其子级以查找 JButton:

Component[] comp = customPanel.getComponents();
for(Component c: comp) {
  if(c is a button i am interested in) {
    c.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           // implement the logic of what happens when button is clicked!
       }
    });
  }
}

Unless I'm reading this wrong, when you have added the JPanel yourself, you can just add an actionlistener to the button.

JButton.addActionListener(... some listener);

Or is it something else that you are asking here? e.g. if the custom JPanel is not developed by you. Then in that case, see if the panel exposes an API to add a listener to its buttons, if not then the last option is to iterate over its children to find the JButton:

Component[] comp = customPanel.getComponents();
for(Component c: comp) {
  if(c is a button i am interested in) {
    c.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           // implement the logic of what happens when button is clicked!
       }
    });
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文