I am trying to launch multiple JFrames with a custom panel that I created called subpanel
. [In case you are wondering about the naming, I have another class called masterpanel
, which contains a button that launches a new frame containing a new instance of subpanel
.
The purpose of the subpanel
is that when the user hits the enter
button, the color changes. Currently, I have each subpanel
contain an inner class called EnterAction
, which calls setBackground
to change the color.
I was wondering how I can modify this so that I can synchronize the color change between all of my subpanels
.
Currently, I have a variable green
, which I believe I can pass between all of my panels. However, I'm not sure how I can get the EnterAction
to change all of the currently active panels?
I was thinking of creating a list of active subpanels
? But will this cause an additional problem that I would need to maintain the list if the user closes a subpanel
?
Here is my code:
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));
}
}
}
EDIT: There's going to be a maximum of 5 panels. This eliminates the need to create a list maintain active panels.