摆动面板颜色变化

时间:2013-05-05 15:56:55

标签: java swing events jpanel awt

我正在尝试使用我创建的名为subpanel的自定义面板启动多个JFrame。 [如果您想知道命名,我有另一个名为masterpanel的类,其中包含一个按钮,用于启动包含新subpanel实例的新帧。

subpanel的目的是当用户点击enter按钮时,颜色会发生变化。目前,我每个subpanel都包含一个名为EnterAction的内部类,它调用setBackground来更改颜色。

我想知道如何修改它,以便我可以同步所有subpanels之间的颜色变化。

目前,我有一个变量green,我相信我可以在所有面板之间传递。但是,我不确定如何让EnterAction更改所有当前活动的面板?

我在考虑创建一个活跃的subpanels列表?但如果用户关闭subpanel,这会导致我需要维护列表的其他问题吗?

这是我的代码:

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;

public class SubPanel extends javax.swing.JPanel
{   
    private Action enterAction;

    public SubPanel() 
    {
        initComponents();
        enterAction = new EnterAction();

            //KeyBindings on the enter button
        this.getInputMap().put(KeyStroke.getKeyStroke( "ENTER" ), "doEnterAction");
        this.getActionMap().put( "doEnterAction", enterAction );
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setForeground(new java.awt.Color(1, 1, 1));
        setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        
    // Variables declaration - do not modify                     
    // End of variables declaration                   

    private static int green = 240;

    private class EnterAction extends AbstractAction 
    {   
        @Override
        public void actionPerformed(ActionEvent ae) 
        {
            //System.out.println("Enter button is pressed");
            green -= 5;
            if (green <= 0) green = 0;
            setBackground(new java.awt.Color(255, green, 255));
        }
    }
}

编辑:最多会有5个面板。这消除了创建列表维护活动面板的需要。

2 个答案:

答案 0 :(得分:2)

相反,请创建一个包含当前颜色的PanelColorModel。让感兴趣的小组使用建议observer pattern之一的here实现之一注册为此模型的监听者。然后你的Action可以更新模型,听众可以做出相应的反应。

答案 1 :(得分:0)

您可以尝试定义static颜色属性,因此每次按Enter键时,每个子面板都将具有相同的颜色。类似的东西:

static Color subpanelBackgroundColor; //Every instance will have this.
相关问题