CardLayout not working properly - java

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.

Related

Click a button to open a new JFrame / GUI,

I seem to not be able to find a way to get my code to work.
I am making a program and until now everything was working, i have some buttons and they do what they should.
But now i added a button that when a user click it, it should close the current GUI and open a new one.
I also want to point out that i created a new class for this new GUI.
The other GUI class that i want to call is the GuiCrafting, in that class the GUI is also all coded, and works if i call it on the Main.
My question is what do i type here (I tried a lot of things like dispose() etc but i just get error messages) :
public void actionPerformed(ActionEvent event) {
if( str.equals("Crafting")){
//insert code to call the GuiCrafting class and open his GUI
}
Thanks in advance and if you need something more please let me know.
Multiple JFrames are frowned upon as you can read about here and here
Perhaps what you want to use is a CardLayout which manages two or more components (usually JPanel instances) that share the same display space.
After clicking the button "Goto Card 2"
TestApp.java:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApp {
final static String CARD1 = "Card1";
final static String CARD2 = "Card2";
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void initComponents() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
// card 1 components
JButton buttonGotoCard2 = new JButton("Goto Card 2");
buttonGotoCard2.addActionListener((ActionEvent e) -> {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, CARD2);
});
// create card 1
JPanel card1 = new JPanel();
card1.add(new JLabel("Card 1"));
card1.add(buttonGotoCard2);
// card 2 components
JButton buttonGotoCard1 = new JButton("Goto Card 1");
buttonGotoCard1.addActionListener((ActionEvent e) -> {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, CARD1);
});
// create card 2
JPanel card2 = new JPanel();
card2.add(new JLabel("Card 2"));
card2.add(buttonGotoCard1);
// add cards to cards panel
cards.add(card1, CARD1);
cards.add(card2, CARD2);
frame.getContentPane().add(cards, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
There is also a JDialog which could be what you want.
HOWEVER
You can easily do something like that (Open a JFrame from another If you must):
TestApp.java:
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class TestApp {
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void initComponents() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel label = new JLabel("JFrame 1");
JButton button = new JButton("Open JFrame 2");
button.addActionListener((ActionEvent e) -> {
this.showNewJFrame(new WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
// here we listen for the second JFrame being closed so we can bring back the main JFrame
mainFrame.setVisible(true);
}
});
// hide the main JFrame
mainFrame.setVisible(false);
});
panel.add(label);
panel.add(button);
mainFrame.add(panel);
mainFrame.pack();
mainFrame.setVisible(true);
}
private void showNewJFrame(WindowAdapter windowAdapter) {
JFrame frame2 = new JFrame();
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // we dont wnat to exit when this JFrame is closed
JPanel panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel2.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel label2 = new JLabel("JFrame 2");
panel2.add(label2);
frame2.add(panel2);
frame2.addWindowListener(windowAdapter);
frame2.pack();
frame2.setVisible(true);
}
}
This produces:
and when the "Open JFrame 2" is clicked:
and when JFrame 2 is closed it brings back the main JFrame via the WindowAdapter#windowClosing.

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 )

trying yo update my JFrame [duplicate]

This question already has answers here:
Replacing JPanel with JPanel in a JFrame
(3 answers)
Closed 8 years ago.
In my Frame i have have a title screen(J Panel) and when i click a button i want it to be replaced with the game screen(another J Panel). i have this code to replace it, but when i click the button to send it to my start method it clears the GUI and it just stays blank.
public void start() {
frame.remove(titlePanel);
frame.repaint();
frame.add(gamePanel);
}
if i add the gamePanel to the frame where i did the titlePanel it works fine so i know it is finding the image.
any help would be much appreciated.
A preferred solution would be to use CardLayout, which will allow you to switch out views easily...
The direct approach (which you are doing now) should be fixed by calling frame.revalidate() after you've added the gamePanel...but I'd still recommend the CardLayout
You have to use frame.revalidate() to get changes working.
Try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class test extends JFrame {
private JPanel contentPane;
JPanel panel1;
JPanel panel2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test frame = new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public 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);
panel1 = new JPanel();
contentPane.add(panel1, BorderLayout.NORTH);
panel1.setBackground(Color.red);
panel2 = new JPanel();
panel2.setBackground(Color.blue);
JButton btnNewButton = new JButton("New button");
contentPane.add(btnNewButton, BorderLayout.SOUTH);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
remove(panel1);
contentPane.add(panel2, BorderLayout.NORTH);
repaint();
validate();
}
});
}
}

Java Swing : JSplitPane split two component equals size at start up

I'm using JSplitPane includes two JScrollPane at each side. I don't know how to make them at equals size at start up. Here is my main code:
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
inputTextArea = new JTextArea();
outputTextArea = new JTextArea();
// put two TextArea to JScrollPane so text can be scrolled when too long
JScrollPane scrollPanelLeft = new JScrollPane(inputTextArea);
JScrollPane scrollPanelRight = new JScrollPane(outputTextArea);
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(650); // still no effect
contentPane.add(splitPane, BorderLayout.CENTER);
I have used splitPane.setDividerLocation(getWidth() / 2); but still no effect.
Please tel me how to fix this.
For more detail. Here is my full code:
package com.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
//import com.controller.Controller;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JTextArea inputTextArea;
public JTextArea outputTextArea;
private JButton inputBtn;
private JButton outputBtn;
private JButton sortBtn;
public JRadioButton firstButton;
public JRadioButton secondButton;
public JRadioButton thirdButton;
JSplitPane splitPane;
//Controller controller;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
// controller = new Controller(this);
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));
/**
* center
* include two TextArea for display text
*/
inputTextArea = new JTextArea();
outputTextArea = new JTextArea();
// put two TextArea to JScrollPane so text can be scrolled when too long
JScrollPane scrollPanelLeft = new JScrollPane(inputTextArea);
JScrollPane scrollPanelRight = new JScrollPane(outputTextArea);
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
contentPane.add(splitPane, BorderLayout.CENTER);
/**
* Top
* Include two button : SelectFile and WriteToFile
* this layout includes some tricky thing to done work
*/
// create new input button
inputBtn = new JButton("Select File");
// declare action. when user click. will call Controller.readFile() method
// (see this method for detail)
inputBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// controller.readFile();
}
});
// create new output button
outputBtn = new JButton("Write To File");
// declare action. when user click. will call Controller.writeFile() method
// (see this method for detail)
outputBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// controller.writeFile();
}
});
// put each button into seperate panel
JPanel tmpPanel1 = new JPanel();
tmpPanel1.add(inputBtn);
JPanel tmpPanel2 = new JPanel();
tmpPanel2.add(outputBtn);
// finnally. put those two pane into TopPane
// TopPane is GridLayout
// by using this. we can sure that both two button always at center of screen like Demo
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
topPanel.add(tmpPanel1);
topPanel.add(tmpPanel2);
contentPane.add(topPanel, BorderLayout.NORTH);
/**
* Bottom panel
* Include all radionbutton and sortbutton
*/
// Group the radio buttons.
firstButton = new JRadioButton("Last Name");
secondButton = new JRadioButton("Yards");
thirdButton = new JRadioButton("Rating");
// add those button into a group
// so . ONLY ONE button at one time can be clicked
ButtonGroup group = new ButtonGroup();
group.add(firstButton);
group.add(secondButton);
group.add(thirdButton);
// create sor button
sortBtn = new JButton("Sort QB Stats");
// add action for this button : will Call Controller.SortFile()
sortBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// controller.sortFile();
}
});
// add all to bottomPanel
JPanel bottomPanel = new JPanel(new FlowLayout());
bottomPanel.add(firstButton);
bottomPanel.add(secondButton);
bottomPanel.add(thirdButton);
bottomPanel.add(sortBtn);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
setTitle("2013 College Quarterback Statistics");
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setVisible(true);
System.out.println("getwidth: " + getWidth());
splitPane.setDividerLocation(getWidth()/2);
}
}
Thanks :)
I got it right for you. I add this;
contentPane.add(splitPane, BorderLayout.CENTER);
splitPane.setResizeWeight(0.5); <------- here :)
And I got rid of the setDviderLocation() at the bottom
Inititally sets the resize wieght property. values are 0.0 to 1.0, a double value percentage to split the pane. There's a whole lot to exaplain about preferred sizes and such that I read about in the JSplitPane tutorial, so you can check it out for yourself.
It really depends on the exact behaviour you want for the split pane.
You can use:
splitPane.setResizeWeight(0.5f);
when you create the split pane. This affects how the space is allocated to each component when the split pane is resized. So at start up it will be 50/50. As the split pane increased in size the extra space will also be split 50/50;
splitPane.setDividerLocation(.5f);
This will only give an initial split of 50/50. As the split pane size is increased, the extra space will all go to the last component. Also, note that this method must be invoked AFTER the frame has been packed or made visible. You can wrap this statement in a SwingUtilities.invokeLater() to make sure the code is added to the end of the EDT.
Initially getWidth() size is 0. Add splitPane.setDividerLocation(getWidth()/2); after setvisible(true). Try,
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
// still no effect
add(splitPane, BorderLayout.CENTER);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setVisible(true);// JFrame setVisible
splitPane.setDividerLocation(getWidth()/2); //Use setDividerLocation here.

CardLayout display Next panel - java Swing

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

Categories

Resources