我正在尝试使用我创建的名为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个面板。这样就无需创建维护活动面板的列表。

最佳答案

而是创建一个保存当前颜色的PanelColorModel。使用建议的observer pattern实现之一,让感兴趣的面板注册为该模型的侦听器。然后,您的here可以更新模型,并且侦听器可以做出相应的反应。

09-26 12:32