1

我在询问制作保持某种状态的组件的正确方法。就像在其中保存颜色的 Jbutton 或保存某个对象的列表项一样。因此,当这些 GUI 组件触发事件时,我可以使用保存的状态对其进行处理。

我的方式是这样的:

1-创建所需组件的子类,例如 Jbutton 的子类。

2-为这个新的子类创建一个监听器:在监听器中检查事件源是否是子类,转换它然后使用存储的数据。

例子:

class ColorButton extends JButton
{
    static class Listener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            Object source = actionEvent.getSource();
            if( source.getClass() == ColorButton.class)
            {
                ColorButton t = (ColorButton) source;
                t.getComponent().setBackground(t.getColor());
            }
        }
    }


    //states i want to be saved
    private Color c;
    private Component comp;

    ColorButton(Component comp, Color c) {
        setColorChanger(comp, c);
    }

    /*   ......
         ......
         rest of constructors added with those additions
         ......
    */
    private void  setColorChanger(Component comp, Color c)
    {
        this.comp = comp;
        this.c = c;
    }

    Color getColor() {
        return c;
    }

    Component getComponent() {
        return comp;
    }

}

我这样使用它:

        JPanel panel = new JPanel();
        ColorButton.Listener l = new ColorButton.Listener();
        JButton b = new ColorButton("Blue", panel, Color.BLUE);
        JButton r = new ColorButton("Red", panel, Color.RED);
        r.addActionListener(l);
        b.addActionListener(l);
        panel.add(b);
        panel.add(r);
        add(panel);

所以我想知道这种方式是否可以或者什么,我觉得为每个应该保持特定状态的组件做这个很无聊,有没有更好的方法?

4

2 回答 2

2

是的,有更好的方法。每个单独的组件对象都应该有自己独立的ActionListener,这样你就不用检查了if( source.getClass() == ColorButton.class),你可以直接通过名称访问组件的字段,根本不用经过source。为此,您必须使用非静态内部类或匿名内部类。该if声明是一种非常老式且非 OOP 的做事方式。

事实上,组件对象本身可以是它自己的ActionListener——但这种风格只允许你有一个 ActionListener,而且组织得不太好。

于 2013-11-07T19:27:13.450 回答
0

更好的方法取决于您想要保持什么样的状态以及您想要使用它。如果没有考虑清楚以便您可以陈述它,就不可能制定一个更好的整体计划来做到这一点。设置颜色是您唯一想做的事情吗?您是否需要在应用程序中混合使用常规 JButton 和 ColorButton?

于 2013-11-07T19:28:09.927 回答