组合 Swing 组件:如何添加添加 ActionListener 的功能? [英] Composing Swing Components: How do I add the ability to add ActionListeners?

查看:40
本文介绍了组合 Swing 组件:如何添加添加 ActionListener 的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过组合多个现有组件来创建一个(简单的,希望如此)自定义 Swing 组件.就我而言,它是一个开关,由一个 JLabel 和两个用于 On 和 Off 的 JButton 组成.我通过扩展 JPanel 开始 OnOffSwitch.构造函数添加子组件,并将自身设置为按钮的 ActionListener.该类有一个 isOn() 方法,用于查询组件的当前状态.

I want to create a (simple, hopefully) custom Swing component by composing several existing components. In my case, it is an on-off switch which consists of a JLabel, and two JButtons for On and Off. I begin OnOffSwitch by extending JPanel. The constructor adds the sub-components, and sets itself up as an ActionListener for the buttons. The class has an isOn() method for querying the current state of the component.

我现在想添加将 ActionListener 添加到 OnOffSwitch 类的功能.我希望通过扩展像 JPanel 这样的 Swing 组件来免费提供此功能,但 JPanel 没有此功能.从源代码来看,每个具有此功能的 Swing 组件都重新实现了它自己:向列表添加侦听器、触发 ActionEvents 等.

I now want to add the ability to add ActionListeners to the OnOffSwitch class. I expected this functionality would come for free by having extended a Swing component like JPanel, but JPanel does not have this functionality. By the looks of the sources, every Swing component which does have this functionality re-implements it itself: the adding listeners to the list, the firing of ActionEvents, etc.

实现我想要的正确方法是什么?我可以从各种 Swing 组件复制/粘贴该代码(或重写它的要点),或者我可以实现我自己的 OnOffSwitchListener 接口.为了保持一致,我的所有组件似乎都应该使用 ActionListeners.

What is the correct way to achieve what I want? I can copy/paste that code from the various Swing components (or re-write the gist of it), or I can implement my own OnOffSwitchListener interface. To be consistent it seems that all my components should use ActionListeners.

推荐答案

我个人认为您不需要自定义 Swing 组件.您的 UI 类无需扩展任何 Swing 类;您不太可能提供太多自定义行为.(我可能会为组成其他人的 JPanel 让步.)

I personally don't think you need a custom Swing component. No need for your UI class to extend any Swing class; you aren't likely to provide much custom behavior. (I might concede for a JPanel that composes others.)

我更喜欢组合而不是继承.拥有一个包含 Swing 数据成员的 UI 类,并为其提供方法以根据需要添加和删除侦听器.您可以通过这种方式更改行为,而无需重写 UI 类.它只不过是一个容器.

I would prefer composition over inheritance. Have a UI class that has Swing data members and give it methods to add and remove Listeners as you need them. You can change the behavior that way without having to rewrite the UI class. It's nothing more than a container.

public class MyUI
{
    private Button b = new Button();

    public void addButtonListener(ActionListener listener) { this.b.addActionListener(listener); }
}

这篇关于组合 Swing 组件:如何添加添加 ActionListener 的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆