Set JTextFields and JButtons position in CardLayout - java

This is a java template i found about Card Layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main {
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(200, 200));
/* Here we be making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton previousButton = new JButton("PREVIOUS");
previousButton.setBackground(Color.BLACK);
previousButton.setForeground(Color.WHITE);
final JButton nextButton = new JButton("NEXT");
nextButton.setBackground(Color.RED);
nextButton.setForeground(Color.WHITE);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
previousButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
And this is my Window1.java
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Window1 extends JPanel
{
/*
* Here this is our first Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JButtons.
*/
private ActionListener action;
public Window1()
{
init();
}
private void init()
{
final JButton clickButton = new JButton("Click ME");
final JButton dontClickButton = new JButton("DON\'T CLICK ME");
final JTextField title = new JTextField(12);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == clickButton)
{
String myString = title.getText();
System.out.println(myString);
}
else if (ae.getSource() == dontClickButton)
{
JOptionPane.showMessageDialog(null, "I told you not to click me!"
, "Wrong Button", JOptionPane.PLAIN_MESSAGE);
}
}
};
clickButton.addActionListener(action);
dontClickButton.addActionListener(action);
add(clickButton);
add(dontClickButton);
add(title);
}
}
Now my problem is that how do i set the position of the textfields and buttons in Window1?
With this code they are set in the center of the view aligned horizontally.
I tried to use title.setLocation(5,5); but it's not working. Any suggestions?

Now my problem is that how do i set the position of the textfields and buttons in Window1?
Rows like Jlabel - JTextField then new row ,and in the end of the page the button
The thing is you're not using any layout managers. The default layout manager for JPanel is FlowLayout, which will do exactly what you're experiencing (horizontal layout of the components).
Getting vertical alignment could be achieved by using different layout managers. You could use a GridBagLayout for all the component, or a GridLayout, or you could nest JPanel with different layout managers. The possibilities are endless. It just comes down to the exact look you want.
See Laying out Components Within a Container to learn how to use different layout managers. I'll give you an example, but don't let it stop you from looking at the tutorials. You need to learn them.
Also besides just positioning of the components layout managers use dynamic sizing either by respecting the preferred of components are not respecting them. You can see a picture in this answer of some of the layout managers that do and don't respect preferred sizes.
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class LayoutManagers extends JPanel{
public LayoutManagers() {
JLabel label = new JLabel("Text Field");
JTextField textField = new JTextField(20);
JRadioButton rb1 = new JRadioButton("Radio 1");
JRadioButton rb2 = new JRadioButton("Radio 2");
JButton button = new JButton("Button");
JPanel panel1 = new JPanel();
panel1.add(label);
panel1.add(textField);
JPanel panel2 = new JPanel();
panel2.add(rb1);
panel2.add(rb2);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel3.add(button);
JPanel panel4 = new JPanel(new GridLayout(3, 1));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
setLayout(new GridBagLayout());
add(panel4);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new LayoutManagers());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}

Related

Switching Two JPanels on same JFrame [duplicate]

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.

Access and change size of Components placed on a JDialog

I created a modal JDialog (to be correct, a children of JDialog) and set it visible when the user clicks on a JButton on a JFrame. To make sure the content on the JDialog is vertically centered I've overridden the setVisible() method and do some operations before calling super.setVisible(true). The problem here is that no component, that's placed on the dialog, does have an other size than 0 before calling setVisible(true) if the dialog is set to be modal. Also setVisible() does block the execution.
Any suggestions/tips how to bypass/fix this issue?
Sample code:
public class SampleDialog extends JDialog {
protected JPanel contentPane;
public SampleDialog() {
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
JPanel headerPane = new JPanel();
headerPane.setBackground(Color.GREEN);
add(headerPane, BorderLayout.NORTH);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
add(contentPane, BorderLayout.CENTER);
JPanel footerPane = new JPanel();
footerPane.setBackground(Color.YELLOW);
add(footerPane, BorderLayout.SOUTH);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JLabel("Code"));
contentPane.add(new JTextField());
contentPane.add(new JLabel("Password"));
contentPane.add(new JPasswordField());
contentPane.add(new JButton("Login"));
}
#Override
public void setVisible(boolean b) {
/*
* Get total height of all components added to 'contentPane'
* Place Box.createVerticalStrut() before and after the 'contentPane' components,
* so the input fields look like they are centered vertically
* !!! Cannot determine size of any component because it is not rendered
*/
super.setVisible(b);
}
}
to make sure the content on the JDialog is vertically centered i've overriden the setVisible()
You should NOT be overriding setVisible() for this.
To center the component use an appropriate layout manager.
For example to center components vertically and horizontally you can just use a GridBagLayout:
JDialog dialog = new JDialog();
dialog.setLayout( new GrigBagLayout() );
JPanel panel = new JPanel(...);
panel.add(...);
dialog.add(panel, new GridBagConstraints());
You can use MigLayout manager to easily create your intended layout:
package com.zetcode;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
* Centering components on screen.
* Author Jan Bodnar
* Website zetcode.com
*/
class MyDialog extends JDialog {
public MyDialog() {
initDialog();
}
private void initDialog() {
JLabel lbl1 = new JLabel("Code");
JTextField field1 = new JTextField(15);
JLabel lbl2 = new JLabel("Password");
JPasswordField field2 = new JPasswordField(15);
JButton btn = new JButton("Login");
createLayout(lbl1, field1, lbl2, field2, btn);
setTitle("Login");
setLocationRelativeTo(null);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("wrap, align 50% 50%", "[center]"));
add(arg[0]);
add(arg[1]);
add(arg[2]);
add(arg[3]);
add(arg[4]);
pack();
}
}
public class MigLayoutCenterEx extends JFrame {
public MigLayoutCenterEx() {
initUI();
}
private void initUI() {
JPanel pnl = new JPanel();
JButton btn = new JButton("Show dialog");
btn.addActionListener((ActionEvent e) -> {
JDialog dialog = new MyDialog();
dialog.setVisible(true);
});
pnl.add(btn);
add(pnl);
setSize(400, 300);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCenterEx ex = new MigLayoutCenterEx();
ex.setVisible(true);
});
}
}
Screenshot:

Temporarly Cover JFrame with JPanel [duplicate]

How to make an added JPanel visible inside a parent JPanel?
I am using Netbeans for designing my UI.
I have a MainFrame.java, which contains two panels; namely headerPanel and bodyPanel.
In headerPanel I have put three buttons,let it be button1, button2 and button3.
Also I have created three separate files extending JPanel, name it panel1, panel2 and panel3.
Then I added all my three panels inside bodypanel in MainFrame.java in constructor.
bodyPanel.add(panel1);
bodyPanel.add(panel2);
bodyPanel.add(panel3);
I want that on clicking the respective buttons only respective panels should appear in the bodypanel in mainframe, i.e. if I click button1 then panel1 should be displayed.
I have already tried the following code in button1 mouse listener method:
bodyPanel.validate();
bodyPanel.getComponent(0).setVisible(true);
But panel1 does not appear. I did it cause added components in a panel are allotted index. So first I tried to get the components and then make it visible. It did not work.
Use a CardLayout, as shown here.
your requirement truely full filled by CARD LAYOUT
see this example link
and below example Link
the perfect code for your problem case is
package panels.examples;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame implements ActionListener
{
JPanel headerPanel;
JPanel bodyPanel;
JPanel panel1,panel2,panel3;
JButton button1,button2,button3;
Container con;
CardLayout clayout;
public MainFrame()
{
//con=getContentPane();
clayout=new CardLayout();
headerPanel=new JPanel();
bodyPanel=new JPanel(clayout);
button1=new JButton("button1");
button2=new JButton("button2");
button3=new JButton("button3");
//add three buttons to headerPanel
headerPanel.add(button1);
headerPanel.add(button2);
headerPanel.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
panel1=new JPanel();
panel1.add(new JLabel("Panel1"));
panel1.setBackground(Color.pink);
panel2=new JPanel();
panel2.add(new JLabel("Panel2"));
panel2.setBackground(Color.gray);
panel3=new JPanel();
panel3.add(new JLabel("Panel3"));
//add above three panels to bodyPanel
bodyPanel.add(panel1,"one");
bodyPanel.add(panel2,"two");
bodyPanel.add(panel3,"three");
setLayout(new BorderLayout());
setSize(600,450);
add(headerPanel,BorderLayout.NORTH);
add(bodyPanel,BorderLayout.CENTER);
// headerPanel.setBounds(0,0,600,100);
bodyPanel.setBounds(0,100, 600, 500);
setVisible(true);
}
public static void main(String args[])
{
new MainFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1)
{
clayout.show(bodyPanel, "one");
}
else if(e.getSource()==button2)
{
clayout.show(bodyPanel, "two");
}
else if(e.getSource()==button3)
{
clayout.show(bodyPanel, "three");
}
}
}
out put
Use the CardLayout. Below is a Helper class that I have written. Hope it helps.
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* #author Dchan(Dulitha Wijewantha)
*
* This class is used to switch Cards in a CardLayout
*
* #version $Revision: 1.0 $
*/
public class CardLayoutHelper {
private JPanel panel;
private CardLayout layout;
/**
*
* #param panel JPanel
*/
public CardLayoutHelper(JPanel panel) {
this.panel = panel;
this.layout = (CardLayout) this.panel.getLayout();
}
public CardLayoutHelper(JPanel panel, JPanel... panels){
this(panel);
for (int i = 0; i < panels.length; i++) {
JPanel jPanel = panels[i];
panel.add(jPanel.getName(), jPanel);
}
}
/**
*
* #param currentPanel
* - The panel that will be switched into the view
*/
public void switchPanel(JPanel currentPanel) {
panel.removeAll();
panel.add(currentPanel, currentPanel.getName());
layout.show(panel, currentPanel.getName());
panel.revalidate();
panel.repaint();
}
public void switchPanel(String name){
layout.show(panel, name);
panel.revalidate();
panel.repaint();
}
}

Toggling/navigating jpanels in java swings

> I have a jframe defined in a package 'abc'. this jframe acts as a main class too.
> the same package 'abc' also contain 4 jpanels(panel1,panel2,panel3,panel4) defined in different java classes.
how one should call/show these different jpanels from main jframe class at user clicks on different buttons ?
what if I've got 40-50 such jpanels.what would be the most efficient way to toggle these panels from the main class ?
This is a very simple example that uses next() and one button to change panels.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.border.Border;
public class TestCards extends JFrame {
private final CardLayout cl = new CardLayout();
private final JPanel cards = new JPanel(cl);
private final Border border = BorderFactory.createEmptyBorder(60, 60, 60, 60);
public TestCards() {
JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel1 = new JPanel(new GridBagLayout());
panel1.setBorder(border);
panel1.setBackground(Color.RED);
panel1.add(new JLabel("Card 1"));
cards.add(panel1, "First Panel");
JPanel panel2 = new JPanel(new GridBagLayout());
panel2.setBorder(border);
panel2.setBackground(Color.GREEN);
panel2.add(new JLabel("Card 2"));
cards.add(panel2, "Second Panel");
JPanel panel3 = new JPanel(new GridBagLayout());
panel3.setBorder(border);
panel3.setBackground(Color.BLUE);
panel3.add(new JLabel("Card 3"));
cards.add(panel3, "Third Panel");
JButton controlButton = new JButton("Switch");
controlButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.next(cards);
}
});
JPanel controlPanel = new JPanel();
controlPanel.setBackground(Color.LIGHT_GRAY);
controlPanel.add(controlButton);
contentPane.add(cards);
contentPane.add(controlPanel);
cl.show(cards, "First Panel");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
TestCards frame = new TestCards();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
An alternative (among many) would be to use 3 buttons where each one shows a specific panel (by using show instead of next).
See this for more info.
CardLayout's previous and next methods can be used to navigate forward & back respectively through the card components. To make it easier to navigate the components non-consecutively, you could place the card names in a String array:
private static final String[] CARD_NAMES = { "name_2996062106101", ... };
Then, to display a specific cardIndex, you could simply use:
CardLayout layout = (CardLayout) contentPane.getLayout();
layout.show(contentPane, CARD_NAMES[cardIndex]);
For more see How to Use CardLayout.

How can I replace one of two JPanels with another JPanel in Java?

I designed an interface for the welcome screen with one JFrame included two JPanels (JPanel1 on right and JPanel2 on left). The buttons on the left is to switch the Panels in JPanel1. I want to press on a button to replace JPanel1 content with another JPanel but I don`t know how. Please help.
Here is a very simple example of something that should approximate your description. On the left, we have a hug button to toggle the content of the right panel. On the right, you have a panel with a given border and a label. When you press the button, the content on the right is swapped with the other panel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout2 {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel leftPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Left panel");
leftPanel.add(label, BorderLayout.NORTH);
JButton button = new JButton("Toggle right panel");
leftPanel.add(button);
frame.add(leftPanel, BorderLayout.WEST);
final CardLayout cardLayout = new CardLayout();
final JPanel rightPanel = new JPanel(cardLayout);
rightPanel.setPreferredSize(new Dimension(200, 500));
JPanel rightPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
rightPanel1.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel rightPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JLabel label1 = new JLabel("Right panel 1 with a red border");
JLabel label2 = new JLabel("Right panel 2 with a blue borer");
rightPanel1.add(label1);
rightPanel2.add(label2);
rightPanel.add(rightPanel1, "panel1");
rightPanel.add(rightPanel2, "panel2");
frame.add(rightPanel, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(rightPanel);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestCardLayout2().initUI();
}
});
}
}
An alternative to CardLayout would be JRootPane and its JRootPane.setContentPane() method. Here's an example:
final JPanel panel1 = ...;
final JPanel panel2 = ...;
boolean showingPanel1 = true;
final JRootPane rootPane = new JRootPane();
rootPane.setContentPane(panel1);
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (showingPanel1) {
rootPane.setContentPane(panel2);
} else {
rootPane.setContentPane(panel1);
}
showingPanel = !showingPanel;
}
});
Add the rootPane and switchButton components to your window, and then clicking switchButton will switch out the panels.
Here's a tutorial. You should mostly be concerned with JRootPane.setContentPane, the other stuff in the tutorial isn't relevant.
The best answer I found is that I will create one JFrame only and gonna make one big JPanel include two JPanels (JPanelLeft include the buttons and JPanelRight include what the button do) then I will copy the main JPanel for each JButton.
When I press on any button I will do (JFrame.getContentPane.removeAll) to remove the old JPanel then (JFrame.getContentPane.Add(NewJPanel).
This works for me and keep my design as I Want. Thanks for every body.

Categories