CardLayout display Next panel - java Swing - java

I am having some problem with CardLayout. I have a panel and a Next button on it. upon clicking on it i want to display the 2nd panel. In my code, when i click on the Next buton, the next panel is not displayed. Can someone help me solve this ?
package com.test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CardLay extends JFrame {
private JPanel contentPane;
private CardLayout ca;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CardLay frame = new CardLay();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CardLay() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
ca =new CardLayout(0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(ca);
JPanel panel = new JPanel();
panel.setLayout(null);
contentPane.add("1",panel);
JButton btnNext = new JButton("NEXT");
btnNext.setBounds(131, 93, 117, 29);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ca.show(contentPane,"1");
System.out.println("button clicked");
}
});
panel.add(btnNext);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, "name_1353086933711396000");
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel_1.add(chckbxNewCheckBox);
}
}

You need to call:
ca.show(contentPane, "name_1353086933711396000");
For this to work you will have to add the second panel like this:
contentPane.add("name_1353086933711396000", panel_1);
When using CardLayout make sure to keep navigation buttons on a separate container other then the 'cards' themselves, so that they can be visible throughout the navigation process. Here you could place a new navigation container in the frame's BorderLayout.SOUTH position. For sequential navigation, the methods previous and next are available.
Also avoid using absolute positioning (null layout). See Doing Without a Layout Manager (Absolute Positioning).
public CardLay() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 400);
ca = new CardLayout(0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(ca);
JPanel panel1 = new JPanel();
panel1.add(new JButton("Test Button"));
contentPane.add("card1", panel1);
JPanel panel2 = new JPanel();
contentPane.add("card2", panel2);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel2.add(chckbxNewCheckBox);
JPanel navigationPanel = new JPanel();
JButton btnPrevious = new JButton("< PREVIOUS");
btnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca.previous(contentPane);
}
});
navigationPanel.add(btnPrevious);
JButton btnNext = new JButton("NEXT >");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca.next(contentPane);
}
});
navigationPanel.add(btnNext);
add(contentPane);
add(navigationPanel, BorderLayout.SOUTH);
}
Recommended: How to Use CardLayout

Related

Why isn't the first panel showing in my cardlayout

Sorry for the code dump but Im not sure where is causing the issue. When I click the Round Robin button its supposed to take me to the RoundRobin page (which it does) but then I should be able to click the start and the center panel which is blue should yellow animation panel which is yellow. When I run this, I just see the yellow animation panel and when I click start I get a "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout" error.
/**
* #description:scheduling algoritmn visualisation app
* #version: 1.0
* #date created: 22/11/2020
*/
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.net.*;
public class SchedulingAlgorithms extends JFrame{
CardLayout cl;
JPanel contentPane;
Container deckPanel;
Image image;
/**
* Constructor for objects of class SchedulingAlgorithms
*/
public SchedulingAlgorithms(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 658, 336);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel headerPanel = new JPanel();
JLabel label = new JLabel();
headerPanel.setBackground(Color.LIGHT_GRAY);
headerPanel.setBounds(5, 5, 125, 106);
contentPane.add(headerPanel);
try{
URL url = new URL("file:C:///Users//alyssa//Scheduling_Animations//icon.png");
image=ImageIO.read(url);
headerPanel.add(new JLabel(new ImageIcon(image)));
}catch (IOException e) {
e.printStackTrace();
}
JPanel btnPanel = new JPanel();
btnPanel.setBackground(Color.LIGHT_GRAY);
btnPanel.setBounds(5, 111, 125, 181);
contentPane.add(btnPanel);
btnPanel.setLayout(null);
cl= new CardLayout();
JPanel deckPanel = new JPanel();
deckPanel.setBounds(140, 5, 492, 287);
contentPane.add(deckPanel);
deckPanel.setLayout(cl);
JPanel home = new JPanel();
deckPanel.add(home, "home");
JPanel homePic = new JPanel(new GridLayout(2,1));
home.add(homePic, "homePic");
JLabel instructions1 = new JLabel();
instructions1.setText("Select a scheduling algorithm to see it's visual representation");
homePic.add(instructions1);
try{
URL url = new URL("file:C:///Users//alyssa//Scheduling_Animations//schedule.png");
image=ImageIO.read(url);
homePic.add(new JLabel(new ImageIcon(image)));
}catch (IOException e) {
e.printStackTrace();
}
JPanel card1 = new JPanel();
deckPanel.add(card1, "rr");
card1.setLayout(new BorderLayout());
JLabel txt2= new JLabel();
txt2.setText("Round Robin: Set the boundaries of the animation");
card1.add(txt2);
JPanel card2 = new JPanel();
deckPanel.add(card2, "fcfs");
JTextArea txt3 = new JTextArea();
txt3.setText("First-Come-First-Served");
card2.add(txt3);
JPanel card3 = new JPanel();
deckPanel.add(card3, "sjf");
JTextArea txt4 = new JTextArea();
txt4.setText("Shortest Job First");
card3.add(txt4);
JPanel card4 = new JPanel();
deckPanel.add(card4, "ps");
JTextArea txt5 = new JTextArea();
txt5.setText("Priority Scheduling");
card4.add(txt5);
JButton btn0 = new JButton("Home");
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="Home")
cl.show(deckPanel, "home");
}
});
btn0.setBounds(10, 11, 89, 23);
btnPanel.add(btn0);
JButton btn1 = new JButton("Round Robin");
btn1.setBounds(10, 45, 89, 23);
btnPanel.add(btn1);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="Round Robin")
cl.show(deckPanel, "rr");
}
});
JButton btn2 = new JButton("First-Come-First-Served");
btn2.setBounds(10, 79, 89, 23);
btnPanel.add(btn2);
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="First-Come-First-Served")
cl.show(deckPanel, "fcfs");
}
});
JButton btn3 = new JButton("Shortest Job First");
btn3.setBounds(10, 113, 89, 23);
btnPanel.add(btn3);
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="Shortest Job First")
cl.show(deckPanel, "sjf");
}
});
JButton btn4 = new JButton("Priority Scheduling");
btn4.setBounds(10, 147, 89, 23);
btnPanel.add(btn4);
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="Priority Scheduling")
cl.show(deckPanel, "ps");
}
});
JPanel northPanel=new JPanel();
card1.add(northPanel,BorderLayout.NORTH);
JLabel heading=new JLabel();
heading.setText("Round Robin.");
northPanel.add(heading);
JLabel instructions2= new JLabel();
instructions2.setText("Set the boundaries of the animation");
northPanel.add(instructions2);
JPanel centerPanel=new JPanel();
centerPanel.setBackground(Color.blue);
card1.add(centerPanel,BorderLayout.CENTER);
centerPanel.setLayout(new CardLayout());
JPanel animPanel=new JPanel();
animPanel.setBackground(Color.yellow);
centerPanel.add(animPanel,"anim");
JPanel southPanel=new JPanel();
card1.add(southPanel,BorderLayout.SOUTH);
JButton start = new JButton("START");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="START")
cl.show(centerPanel, "anim");
}
});
start.setBounds(311, 159, 65, 23);
southPanel.add(start);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SchedulingAlgorithms frame = new SchedulingAlgorithms();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You set the layout for the "deckPanel" using variable "cl" as the reference to the layout manager:
deckPanel.setLayout(cl);
But then you try to change the card on the "centerPanel":
if(e.getActionCommand()=="START")
cl.show(centerPanel, "anim");
You can't share CardLayout references. If you want the "centerPanel" to also use a CardLayout, then you need to keep a separate refence for that layout manager. So you really need "deckLayout" and "centerLayout" variables for the individual layout managers. This is why variable names should be descriptive, so you know how the variable can be used.
Don't use "==" for object comparison. Instead use the equals(...) method.

How to refresh JInternalFrame or JPanel form on button click where JPanel is a separate class and used in JInternalFrame

Iam trying to build a desktop application with multiple screens inside one single JFrame.
So each button click event will take us to the separate screen with refreshed components in the screen. So far this approach is working for me but the problem I am facing is even after using ".dispose(), .repaint(), .revalidate(), .invalidate()" functions. JInternalFrame or Jpanel seems to not refresh its components.
Which works something like below gif.
Tabbed Style
I do know JtabbedPane exists but for my method JtabbedPane is not viable.
Below I am posting minified code by replicating the problem I am facing.
MainMenu.Java(file with Main Class)
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
public class MainMenu extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 522);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 807, 63);
contentPane.add(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
JButton Tab1 = new JButton("Tab1");
panel.add(Tab1);
JButton Tab2 = new JButton("Tab2");
panel.add(Tab2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 88, 807, 387);
contentPane.add(scrollPane);
JInternalFrame internalFrame1 = new JInternalFrame();
JInternalFrame internalFrame2 = new JInternalFrame();
Tab1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel1 panel1 = new Panel1();
if(internalFrame1 !=null) {
internalFrame1.dispose();
panel1.invalidate();
panel1.revalidate();
panel1.repaint();
}
internalFrame1.setTitle("Panel 1");
scrollPane.setViewportView(internalFrame1);
internalFrame1.getContentPane().add(panel1);
internalFrame1.setVisible(true);
}
});
Tab2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel2 panel2 = new Panel2();
if(internalFrame2 !=null) {
internalFrame2.dispose();
panel2.invalidate();
panel2.revalidate();
panel2.repaint();
}
internalFrame2.setTitle("Panel 2");
scrollPane.setViewportView(internalFrame2);
internalFrame2.getContentPane().add(panel2);
internalFrame2.setVisible(true);
}
});
}
}
and the corresponding Jpanel class files where JInternal Frames
Panel1.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel1 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel1() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Example Button");
btnNewButton.setBounds(10, 156, 430, 21);
add(btnNewButton);
}
}
Panel2.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel2 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel2() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button2");
btnNewButton.setBounds(21, 157, 419, 21);
add(btnNewButton);
}
}
P.S: This is my first time asking question in Stackoverflow so forgive me and if possible guide me if i miss anything
Thank you :)
Edit:
The problem I am facing is on the surface it looks like the Jpanel has been refreshed but the components like JtextField Still hides the previously written text in it and only show the text when i click on that JTextField
Below I am Attaching another gif which show highlights the issue. I have highlighted the part where I am facing issue.
Issue I am Facing
The dispose() method does not remove components so you keep adding components to the internal frame when you use the following:
internalFrame1.getContentPane().add(panel1);
Instead you might do something like:
Container contentPane = internalFrame1.getContentPane();
contentPane.removeAll();
contentPane.add( panel1 );
contentPane.revalidate();
contentPane.repaint();
You can use the JPanels in the Jframes and then use the CardLayout to change the panel ( which could than act like the different screens )

Java swing gui change background of jlabel and make it reset

I have a gui that has:
a label at the top
a JFrame at the bottom with 2 Buttons called left and right
a panel in center that is gridlayout with 2 JLabel to either display an image or change the back ground color. (currently the background color is set to black for both jLabels).
*what I would like to happen.
When you click on button "left" the image appears on lblPicture1 and lblPicture2 has a black background and no image. and vise versa for the right button. and when you click on the left again, it repeats this cycle.
I accomplish that however, when i click the left and right button I just have two images and neither one has a black background.
I belive this is due to the image not resetting.
Can you direct me to the right place on how I can get this to work?
Thank you
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ExampleGUI extends JFrame {
private JPanel contentPane;
private JLabel lblPicture1;
private JLabel lblPicture2;
private int change;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleGUI frame = new ExampleGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblExampleGui = new JLabel("Example GUI");
lblExampleGui.setBorder(new EmptyBorder(8, 0, 8, 0));
lblExampleGui.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
lblExampleGui.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblExampleGui, BorderLayout.NORTH);
JPanel panelButton = createPanelButton();
contentPane.add(panelButton, BorderLayout.SOUTH);
JButton btnLeft = createBtnLeft();
panelButton.add(btnLeft);
JButton btnRight = createBtnRight();
panelButton.add(btnRight);
JPanel panelCenter = createPanelCenter();
contentPane.add(panelCenter, BorderLayout.CENTER);
JLabel lblPicture1 = createLblPicture1();
panelCenter.add(lblPicture1);
JLabel lblPicture2 = createPicture2();
panelCenter.add(lblPicture2);
}
public JLabel createPicture2() {
lblPicture2 = new JLabel();
lblPicture2.setOpaque(true);
lblPicture2.setBackground(Color.BLACK);
return lblPicture2;
}
public JLabel createLblPicture1() {
lblPicture1 = new JLabel();
lblPicture1.setOpaque(true);
lblPicture1.setBackground(Color.BLACK);
//lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
return lblPicture1;
}
public JPanel createPanelCenter() {
JPanel panelCenter = new JPanel();
panelCenter.setLayout(new GridLayout(0, 2, 8, 0));
return panelCenter;
}
public JButton createBtnRight() {
JButton btnRight = new JButton("right");
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture1.setBackground(Color.BLACK);
lblPicture2.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnRight.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnRight;
}
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}
public JPanel createPanelButton() {
JPanel panelButton = new JPanel();
return panelButton;
}
}
The background is painted beneath the icon, so if the icon is not reset, then it will continue to be displayed.
You can simply set the icon property by passing it null, for example
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setIcon(null);
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}

Resizing jpanel according to the components present in it

In the below example, in the west side of the border layout, there is a parent panel which has a BoxLayout and couple of panels inside. The problem is that the west panel covers the whole area from top to bottom. The FlowLayout used for child panels inside the parent panel consume a lot of area. Is it possible to compress each JPanel according to the components? Also, it should remain the same even when the window is maximized?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
public class Sample extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sample frame = new Sample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("New label");
panel.add(lblNewLabel);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.WEST);
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2);
textField = new JTextField();
panel_2.add(textField);
textField.setColumns(2);
textField_1 = new JTextField();
panel_2.add(textField_1);
textField_1.setColumns(2);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel_3.add(chckbxNewCheckBox);
JPanel panel_4 = new JPanel();
panel_1.add(panel_4);
JButton btnNewButton = new JButton("New");
panel_4.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New");
panel_4.add(btnNewButton_1);
}
}
One approach is to add panel_1 to an enclosing panel. The default FlowLayout conforms itself to the preferred size of the enclosed components when you pack() the enclosing Window. I've added a gray panel to CENTER as a placeholder; resize the frame to see the effect.
JPanel flowPanel = new JPanel();
flowPanel.add(panel_1);
As tested:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
public class Sample extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Sample frame = new Sample();
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("New label");
panel.add(lblNewLabel);
JPanel panel_1 = new JPanel();
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2);
textField = new JTextField();
panel_2.add(textField);
textField.setColumns(2);
textField_1 = new JTextField();
panel_2.add(textField_1);
textField_1.setColumns(2);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
panel_3.add(chckbxNewCheckBox);
JPanel panel_4 = new JPanel();
panel_1.add(panel_4);
JButton btnNewButton = new JButton("New");
panel_4.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New");
panel_4.add(btnNewButton_1);
JPanel flowPanel = new JPanel();
flowPanel.add(panel_1);
contentPane.add(flowPanel, BorderLayout.WEST);
contentPane.add(new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
#Override
public Color getBackground() {
return Color.lightGray;
}
}, BorderLayout.CENTER);
}
}

CardLayout not working properly

I have written this simple Cardlayout example with Splitpane, Combobox and few other panels containing buttons and label.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class splitpane_test extends JFrame implements ItemListener {
private JPanel contentPane;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
JPanel cards;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
splitpane_test frame = new splitpane_test();
//frame.addComponentToPane(frame.getContentPane());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public splitpane_test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JSplitPane splitPane = new JSplitPane();
contentPane.add(splitPane, BorderLayout.CENTER);
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = {BUTTONPANEL, TEXTPANEL};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
splitPane.setLeftComponent(comboBoxPane);
//Create the "cards".
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 20));
//Create the panel that contains the "cards".
cards = new JPanel();
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
splitPane.setRightComponent(cards);
cards.setLayout(new CardLayout(0, 0));
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
System.out.print("Event Triggered \n");
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, TEXTPANEL);
}
}
I can see the splitpane with combobox on left and other cardlayout panels on right.
when i change the combobox items nothing is happening on right size.
In order to verify if iam hitting the cardout i used the
System.out.print("Event Triggered \n");
but the surprising thing i have seen is that its displaying twice for each combobox item change as if its calling twice
Event Triggered
Event Triggered
Can you please suggest me what iam doing wrong here and why event triggered is getting hit twice.
Thanks for all your time and help.
Can you please suggest me what I am doing wrong here and why event triggered is getting hit twice.
If you look at the ItemEvent, you'll see that one item is being DESELECTED and the other is being SELECTED. Instead, listen for ActionEvent, as shown here, and select the correct card accordingly.
Addendum: If you implement the helpful changes in #Michael Brewer-Davis's answer, then a suitable ActionListener is particularly straightforward:
#Override
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
Set the layout manager before adding components.
Two items are changing state; one is being deselected, the other selected. You would improve your debugging output with the following:
System.out.println("Event Triggered: " + e);
You'll also need to account for the event switching the selection back--not all changes in the combo box should select TEXTPANEL.

Categories

Resources