繁体   English   中英

创建带有状态的GUI组件

[英]Create GUI components with states

我在问有关制造具有某种状态的组件的正确方法。 就像在其中保存颜色的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);

因此,我想知道这种方法是否可行,或者让每个应该具有特定状态的组件都采用这种方法很无聊,是否有更好的方法?

是的,有更好的方法。 每个组件对象都应具有自己的单独的ActionListener,这样您就不必检查if( source.getClass() == ColorButton.class) ,并且可以按名称直接访问组件的字段,而不必彻底了解source 为此,您必须使用非静态内部类或匿名内部类。 if语句是一种非常老式且非OOP的处理方式。

实际上,组件对象本身可以是其自己的 ActionListener,但是这种样式仅允许您拥有一个ActionListener,而且组织性较差。

更好的方法取决于要保留的状态以及要使用的状态。 如果不考虑透彻做出陈述,就不可能制定出更好的总体计划。 设置颜色是您唯一要做的事情吗? 您是否需要在应用程序中将常规JButton与ColorButtons混合使用?

暂无
暂无

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

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