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

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

问题描述

我想通过组合几个现有组件来创建一个(简单的,有希望的)自定义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.

我现在想要添加将ActionListeners添加到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类,并为其提供在需要时添加和删除Listener的方法。您可以通过这种方式更改行为,而无需重写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组件:如何添加添加ActionListeners的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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