2013-05-05 134 views
1

我试图用我创建的自定义面板启动多个JFrame,调用的内容为subpanel。 [如果你想知道命名,我有另一个类叫masterpanel,其中包含一个按钮,启动一个新的框架,其中包含一个新的实例subpanelSwing Panels颜色变化

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

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

目前,我有一个变量​​,我相信我可以在所有面板之间传递。但是,我不确定如何让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个板。这消除了创建列表维护活动面板的需要。

+0

* “我试图启动多个JFrames” *请参阅[多JFrames,好/坏习惯的用?(http://stackoverflow.com/a/9554657/418556) – 2013-05-05 16:01:20

+0

+1 [[Action]](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html)。 – trashgod 2013-05-05 16:16:43

+0

@AndrewThompson我正在创建一个模型。我想我可以改变我的应用程序的范围。最多可以打开5个窗口。 – Rhs 2013-05-05 16:47:52

回答

2

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

0

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

static Color subpanelBackgroundColor; //Every instance will have this. 
+1

我不认为这是准确的。即使所有面板共享一个静态“颜色”变量,仍然需要为每个面板调用setBackground的事件。 – Rhs 2013-05-06 13:49:10