Change JFrame(without layout) to JPanel - java

I have to change my program's GUI implemented in Swing. Now I have many charts in seperate windows and I want to change it so they all display in only one. The constraction of the orginal version was that
JFrame had a JPanel field. JFrame had no set layout.
private void initComponents() {// GEN-BEGIN:initComponents
getContentPane().setLayout(null);
setTitle("Wykres");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
resizedWindow(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width - MIN_WIDTH) / 2, (screenSize.height - MIN_HEIGHT) / 2, MIN_WIDTH, MIN_HEIGHT);
}
JPanel was declared as follows:
BorderLayout borderLayout = new BorderLayout();
borderLayout.setHgap(0);
borderLayout.setVgap(0);
drawPanel = new JDrawPanel();
drawPanel.setLayout(borderLayout);
drawPanel.setComponentOrientation(ComponentOrientation.UNKNOWN);
setContentPane(drawPanel);
If I remove inheritance by JFrame and add inheritance by JPanel, the method paintComponent is not called. I think the reason is bad layout settings. However program calculates the distances from the edges, and I don't want to change it. How can I easily edit this program?
I also generated new GUI in NETBEANS
public class ViewPanel extends javax.swing.JFrame {
public ViewPanel() {
// initComponents();
}
public ViewPanel(JPanel histo, JPanel dystrybu, JPanel time){
initComponents(histo, dystrybu, time);
}
/**
* 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(JPanel histo, JPanel dystrybu, JPanel time) {
MainTabs = new javax.swing.JTabbedPane();
jHistoTab = histo;
jDystybuTab = dystrybu;
jTimeTab = time;
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("zaleznosc czasowa");
MainTabs.setToolTipText("");
MainTabs.addTab("histogram", jHistoTab);
MainTabs.addTab("dystrybuanta", jDystybuTab);
MainTabs.addTab("zalenosc czasowa", jTimeTab);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MainTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 712, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MainTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
.addContainerGap())
);
MainTabs.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ViewPanel().setVisible(true);
AppSMO.main(null);
}
});
}
public void setHistoTab(JPanel panel){
jHistoTab=panel;
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane MainTabs;
private JPanel jDystybuTab;
private JPanel jHistoTab;
private JPanel jTimeTab;
// End of variables declaration
}

Set a BorderLayout to the contentpane. Add your panel to the contentPane.
That will give it center constraint so it will adapt to the size of the window.
In the panel you are then free to add any components you need. I recommend that you don't use null layout anywhere.
Avoid absolute positioning.

Related

Why won't the JLabels or JButtons show up when running the GUI?

I have been playing around with numerous solutions but none of them seems to work. in the constructor, there is a default initComponents() which I can not change. So I created a second method called myComponents(). The class I am using extends JFrame so I do not need to create another frame in any initializer. I created a JPanel with a vertical Boxlayout, 2 labels, 1 text field, and 1 button. I added the panel to the frame then I added all the components to the panel then packed everything.
I am unsure as to why nothing shows up besides the frame when it is run.
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* #author gpbli
*/
public class MAINFRAME extends javax.swing.JFrame {
/**
* Creates new form MAINFRAME
*/
//MAINFRAME frame = new MAINFRAME();
JPanel homescreen = new JPanel();
JLabel numOfIngredLabel = new JLabel();
JTextField numOfIngred = new JTextField();
JButton okButton = new JButton();
JLabel logo = new JLabel();
ImageIcon img = new ImageIcon("logo_resized.png");
public MAINFRAME() {
initComponents();
myComponents();
}
public void myComponents(){
BoxLayout box = new BoxLayout(homescreen,BoxLayout.Y_AXIS);
homescreen.setLayout(box);
numOfIngredLabel.setText("How many Ingredients");
numOfIngred.setText("");
okButton.setText("OK");
logo.setText(" ");
logo.setIcon(img);
add(homescreen);
homescreen.add(logo);
homescreen.add(numOfIngredLabel);
homescreen.add(numOfIngred);
homescreen.add(okButton);
numOfIngredLabel.setVisible(true);
numOfIngred.setVisible(true);
okButton.setVisible(true);
logo.setVisible(true);
pack();
revalidate();
}
/**
* 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().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)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MAINFRAME().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
The appearance of initComponents() suggests the IDE is expecting the programmer to use the GUI builder, while the myComponents() is the programmer taking control of the GUI construction to code it by hand.
Use one or the other. I'd always use the latter, which does not require the JFrame to be extended. In fact, creating the main view of the GUI in a JPanel and adding that single component to a JFrame is the way we would typically recommend.
Note: See also the accepted answer to: Netbeans GUI editor generating its own incomprehensible code

How to create a JMenuBar with Glossy Colors?

I created a small Swing based application. For that I created a menu bar using JMenuBar class. But I want to apply glossy color for that menu bar.
In particular, I'm look at the effects seen here: a gradient color in the fifth example and an animation in the seventh.
My Code:
public class MenuBar extends javax.swing.JFrame {
/**
* Creates new form MenuBar
*/
public MenuBar() {
initComponents();
}
/**
* 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() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().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, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MenuBar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
While your question is very broad, several points are worth mentioning:
As suggested here, support for CSS in Swing is limited; JavaFX may be an alternative.
In Swing, the appearance of a JMenuItem is controlled by its UI delegate, typically derived from BasicButtonUI; an example of applying a gradient is seen here.
Alternatively, add instances of JButton to a JToolBar, illustrated here; use the rollover property to change the button's icon as desired.
Create animated icons using a Swing Timer, as shown here.

How to Customize the JMenuBar with HTML code [duplicate]

I created a small Swing based application. For that I created a menu bar using JMenuBar class. But I want to apply glossy color for that menu bar.
In particular, I'm look at the effects seen here: a gradient color in the fifth example and an animation in the seventh.
My Code:
public class MenuBar extends javax.swing.JFrame {
/**
* Creates new form MenuBar
*/
public MenuBar() {
initComponents();
}
/**
* 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() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().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, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MenuBar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
While your question is very broad, several points are worth mentioning:
As suggested here, support for CSS in Swing is limited; JavaFX may be an alternative.
In Swing, the appearance of a JMenuItem is controlled by its UI delegate, typically derived from BasicButtonUI; an example of applying a gradient is seen here.
Alternatively, add instances of JButton to a JToolBar, illustrated here; use the rollover property to change the button's icon as desired.
Create animated icons using a Swing Timer, as shown here.

Unusual behavior for the same swing code in netbeans

I have two almost similar code.
Code I
JFrame pFrame=new NetBeansFrame();
JPanel myPanel=new myPanel();
pFrame.add(myPanel);
Dimension windowDim=myPanel.getSize();
pFrame.pack();
pFrame.getContentPane().setSize(windowDim.width-100,windowDim.height-50);
pFrame.setVisible(true);
Code II
JFrame pFrame=new JFrame();
JPanel myPanel=new myPanel();
pFrame.add(myPanel);
Dimension windowDim=myPanel.getSize();
pFrame.pack();
pFrame.getContentPane().setSize(windowDim.width-100,windowDim.height-50);
pFrame.setVisible(true);
In Code I,NetBeansFrame is a frame that I created using netbeans->Jframe and named it NetBeansFrame.It contains nothing.I added the panel into it using codeI.
NetBeansFrame.java
public class NetBeansFrame extends javax.swing.JFrame {
public NetBeansFrame() {
initComponents();
}
/** 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 407, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 429, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NetBeansFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NetBeansFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NetBeansFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NetBeansFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NetBeansFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
In Code II,I am creating a frame from JFrame.Logically both the codes are equivalent.
But on executing Code I,the panel does not appear in netbeansFrame while for Code II the panel appears.
So,I want to know that what may be the cause for this unusual behavior for almost same code.
Dimension windowDim=myPanel.getSize(); returned only Dimension[0, 0], becasue returned Dimension from
already visible container (in your case with components JPanel)
after called pack();
then pFrame.getContentPane().setSize(windowDim.width-100,windowDim.height-50); returned Dimension[-100, -50]
you can
if JPanel is empty then returns its PreferredSize
if JPanel is not empty, then its JComponents returns PreferredSize you can to try that with to remove/disable code line pFrame.getContentPane().setSize(windowDim.width-100,windowDim.height-50);

Using CardLayout in Java

I'm currently trying to make a game with a menu.
Menu looks like this.
http://puu.sh/xGoC
Ideally, when I push a button, it will bring me to the game.
The game looks like this.
http://puu.sh/xGoV
I currently initialize a JFrame() in my main class which runs either the menu class or the game class (Both of which are JPanels).
How would I go about using CardLayout to make it so that I can initialize the game menu and when I click a button, change the panel to the game panel?
I've got some sample code for you, it's not perfect, but it should work. Basically, you want to use the NEXT or PREVIOUS calls on the layout manager.
As there's only two panels, I just use the NEXT call to cycle through them. It's probably the best if you read the Swing documentation though, this works, but you might have other requirements as well.
import java.awt.CardLayout;
public class CardLayoutUsage extends javax.swing.JFrame {
public CardLayoutUsage() {
initComponents();
}
/**
* 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() {
containerPanel = new javax.swing.JPanel();
menuPanel = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
gamePanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
containerPanel.setLayout(new java.awt.CardLayout());
menuPanel.setBackground(new java.awt.Color(153, 255, 255));
jButton2.setText("Go to Game");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout menuPanelLayout = new javax.swing.GroupLayout(menuPanel);
menuPanel.setLayout(menuPanelLayout);
menuPanelLayout.setHorizontalGroup(
menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
.addContainerGap(135, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(149, 149, 149))
);
menuPanelLayout.setVerticalGroup(
menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
.addContainerGap(141, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(134, 134, 134))
);
containerPanel.add(menuPanel, "card2");
gamePanel.setBackground(new java.awt.Color(255, 255, 204));
jButton1.setText("Go to Menu");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
gamePanel.setLayout(gamePanelLayout);
gamePanelLayout.setHorizontalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
.addContainerGap(138, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(147, 147, 147))
);
gamePanelLayout.setVerticalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
.addContainerGap(152, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(123, 123, 123))
);
containerPanel.add(gamePanel, "card3");
getContentPane().add(containerPanel, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout)(containerPanel.getLayout());
cl.next(containerPanel);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout)(containerPanel.getLayout());
cl.next(containerPanel);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CardLayoutUsage().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel containerPanel;
private javax.swing.JPanel gamePanel;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel menuPanel;
// End of variables declaration
}
Don't use CardLayout for that.
Instead, remove the menu panel from the frame's content pane and add the game panel.
Remember to validate() the frame as well. Something like this:
public static final int VIEW_MENU = 0;
public static final int VIEW_GAME = 1;
private static Container content;
...
content = frame.getContentPane();
public static void setView(int view){
if(view == VIEW_MENU){
content.remove(menuPanel);
content.add(gamePanel);
} else {
content.remove(gamePanel);
content.add(menuPanel);
}
frame.validate();
}
In the program that I'm currently working on I have a class called ViewManager that creates static instances of each view and adds them to an array with indices that correspond to the constant fields. I also have fields to keep track of previous views for breadcrumbs / going back. It might be a case of re-inventing the wheel, but it allows you to control everything about it. And it's efficient.

Categories