setlayout when dynamic adding textField - java

I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel. I need to add JTextfield and JLabel to panel1 and I add panel1 to panel. I need to add JTextFields and JLabels in a Top-Bottom manner and set layout. panel1 and panel are instances of JPanel.
My code :
public class MakeScrollablePanel extends JFrame implements ActionListener
{
static JButton jButton11,jButton12;
static JPanel panel,panel1;
static JTextField jTextFields;
static JLabel label;
static JComboBox<String> jComboBox;
static Dimension dime,dime1,dime2,dime3,dime4,dime5;
static JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
BoxLayout bx=null;// #jve:decl-index=0:
int count=1,i=0;
public MakeScrollablePanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11);
add(scroll);
dime=new Dimension(600,550);
setSize(dime);
setTitle("Priyank Panel");
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
private void Show()
{
jButton11=new JButton("Add Designation");
panel=new JPanel();
bx=new BoxLayout(panel,BoxLayout.Y_AXIS);
scroll=new JScrollPane(panel);
dime1=new Dimension(500,3000);
dime5=new Dimension(500,450);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230 , 255));
jButton11.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==jButton11)
{
label=new JLabel("Add Designation "+count +" :-");
jTextFields=new JTextField(30);
panel1=new JPanel();
panel1.setBackground(new Color(204, 230 , 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel1.revalidate();
panel.revalidate();
panel.updateUI();
count++;
i++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}

still not working
still I can't see thre any problem with (depsite fact that there is used BoxLayout instead of GridLayout, but result could be very similair in the case that is used many JTextFields)
.
.
from (little bit) modifyied OPs code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MakeScrollablePanel extends JFrame implements ActionListener {
private JButton jButton11, jButton12;
private JPanel panel, panel1;
private JTextField jTextFields;
private JLabel label;
private JComboBox<String> jComboBox;
private Dimension dime, dime1, dime2, dime3, dime4, dime5;
private JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
private BoxLayout bx = null;// #jve:decl-index=0:
private int count = 1, i = 0;
public MakeScrollablePanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11, BorderLayout.NORTH);
add(scroll);
setTitle("Priyank Panel");
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
private void Show() {
jButton11 = new JButton("Add Designation");
panel = new JPanel();
bx = new BoxLayout(panel, BoxLayout.Y_AXIS);
scroll = new JScrollPane(panel);
dime5 = new Dimension(500, 150);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230, 255));
jButton11.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton11) {
label = new JLabel("Add Designation " + count + " :-");
jTextFields = new JTextField(30);
panel1 = new JPanel();
panel1.setBackground(new Color(204, 230, 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel.revalidate();
panel.repaint();
count++;
i++;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}

Related

how to do keypress event in jpanel text field?

when i select something in combobox :
it show joptionPane Dialog box wiht two inputs.
here i want to first focusing amount field and then, when i entered in amount field its goes to no of App field then enter go to OK .
Here is my code for JOption Dialog:
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Amount:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("No of App:"));
myPanel.add(yField);
int value = 0;
xField.requestFocus();
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Amount and No.of app", JOptionPane.OK_CANCEL_OPTION);
You simply try to focus a component which is not layout in a window.
Replace
xField.requestFocus();
by
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xField.requestFocusInWindow();
}
});
You can create your own JDialog on the event that an item has changed to a new item. Then, you can get values entered in the JDialog and appropriately set the information in your parent. If you want to change the order of focus, use a custom focus policy. If you want to change the traversal focus key to the Enter key, you should re-map the key so that it reacts the same as the Tab key. There are several resources online and on this site with information on how to do that.
You should note that the default focus traversal policy is dependent on the order in which you add you elements to your content panel.
I have created a simple example for you on using a JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RankSelection extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RankSelection frame = new RankSelection();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RankSelection() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Slave", "Peasant", "Minion", "Knight", "Bishop", "Prince", "Coder King"}));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Amount amount = new Amount();
textField.setText(Integer.toString((Integer) amount.getStinkiness().getValue()));
}
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
JLabel lblYourRank = new JLabel("Your Rank");
contentPane.add(lblYourRank, BorderLayout.NORTH);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JLabel lblYourStinkiness = new JLabel("Your Stinkiness:");
panel.add(lblYourStinkiness);
textField = new JTextField();
textField.setEditable(false);
textField.setEnabled(false);
textField.setText("0");
panel.add(textField);
textField.setColumns(10);
pack();
}
}
The custom JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Amount extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JSpinner amount;
private JSpinner stinkiness;
public Amount() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblAmount = new JLabel("Amount:");
amount = new JSpinner();
JLabel lblStinkiness = new JLabel("Stinkiness:");
stinkiness = new JSpinner();
contentPanel.add(lblAmount);
contentPanel.add(amount);
contentPanel.add(lblStinkiness);
contentPanel.add(stinkiness);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setVisible(true);
}
public JSpinner getAmount() {
return amount;
}
public JSpinner getStinkiness() {
return stinkiness;
}
}

JLabel text being cut off

As you can see from the image above some of the text is being cut off :(
Code:
package malgm.school.clockui.ui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import malgm.school.clockui.ClockUI;
import malgm.school.clockui.ResourceLoader;
public class ClockFrame extends JFrame {
private static final long serialVersionUID = 1L;
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 200;
public ClockFrame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
}
public void relocalize() {
//Wipe controls
this.getContentPane().removeAll();
this.setLayout(null);
initComponents();
}
#SuppressWarnings("unused")
private void initComponents() {
setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
speakButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec(ClockUI.dir + "/SpeakingClock.exe");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
FONT: http://www.dafont.com/digital-7.font
Any help will be greatly appreciated
A key to success with Swing layouts is to avoid setLayout(null) and to pack() the enclosing Window. This lets the contained components adopt their preferred sizes, as shown below. To avoid this pitfall, don't invoke setResizable(false).
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/23551260/230513 */
public class ClockFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ClockFrame cf = new ClockFrame();
}
});
}
public ClockFrame() {
setTitle("Clock");
setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
#SuppressWarnings("unused")
private void initComponents() {
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
JLabel time = new JLabel("00:00");
time.setFont(time.getFont().deriveFont(72f));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
After
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
Add time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
After it will look like:
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
change your constructor definition to (EDITED)
public Frame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
setSize(850, 650);
setLocationRelativeTo(null);
setVisible(true);
}

How to set Jbuttons to a specific place when you have a background in JLabel : code below

How to set Jbuttons to a specific place when you have a background in JLabel : code below
i can't get the jlabel to stay at the top and the buttons to stay south(bottom) ??
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsClass extends JFrame
implements ActionListener {
JButton b1 = new JButton("button1");
JButton b2 = new JButton("button2");
JButton b3 = new JButton("button3");
JButton b4 = new JButton("button4");
JLabel label = new JLabel("buttons:");
public static void main(String[] args) {
new ButtonsClass();
}
public Jukebox() {
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("image.png")));
setLayout(new FlowLayout());
setSize(500,150);
setTitle("Backgroundwithbuttons");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JPanel top = new JPanel();
top.add(label);
add("North", top);
JPanel bottom = new JPanel();
bottom.add(b1);
bottom.add(b2);
bottom.add(b3);
bottom.add(b4);
add("South", bottom);
setVisible(true);
}
}
" i can't get the jlabel to stay at the top and the buttons to stay south(bottom)"
That's because you set the layout the BorderLayout, then immediately set it to FlowLayout. With FlowLayout, your BorderLayout positioning will do nothing.
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("image.png")));
setLayout(new FlowLayout());
Just get rid of the setLayout(new FlowLayout());
Also your constructor is wrong
public Jukebox() {
-Should be-
public ButtonClass() {
Also you need to set the layout of the JLabel that you set as the content pane. Yout constructor should look like this
public ButtonClass() {
JLabel background = new JLabel(new ImageIcon("image.png"));
background.setLayout(new BorderLayout());
setContentPane(background);
setTitle("Background with buttons");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JPanel top = new JPanel();
top.add(label);
add(top, BorderLayout.NORTH);
JPanel bottom = new JPanel();
bottom.add(b1);
bottom.add(b2);
bottom.add(b3);
bottom.add(b4);
add(bottom, BorderLayout.SOUTH);
//pack();
setVisible(true);
}
Also, add("North", top); is a deprecated method. Instead use add(top, BorderLayout.NORTH) and same for add(bottom, BorderLayout.SOUTH)
Also, Swing apps should be run on the Event Dispatch Thread. You can do so by wrapping the code in your main with a SwingUtilities.invokeLater...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonClass();
}
});
}
Also, you should set the panel's opaque property to false, if you want the image to show behind them.
top.setOpaque(false);
bottom.setOpaque(false);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonClass extends JFrame
implements ActionListener {
JButton b1 = new JButton("button1");
JButton b2 = new JButton("button2");
JButton b3 = new JButton("button3");
JButton b4 = new JButton("button4");
JLabel label = new JLabel("buttons:");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonClass();
}
});
}
public ButtonClass() {
label.setForeground(Color.WHITE);
JLabel background = new JLabel(new ImageIcon(getClass().getResource("/resources/space.png")));
background.setLayout(new BorderLayout());
setContentPane(background);
setTitle("Background with buttons");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JPanel top = new JPanel();
top.setOpaque(false);
top.add(label);
add(top, BorderLayout.NORTH);
JPanel bottom = new JPanel();
bottom.setOpaque(false);
bottom.add(b1);
bottom.add(b2);
bottom.add(b3);
bottom.add(b4);
add(bottom, BorderLayout.SOUTH);
setSize(400, 300);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {}
}
Try using:
add(bottom, BorderLayout.SOUTH);
instead of:
add("South", bottom);
BorderLayout tutorial

Dynamically add components to a JDialog on button click

I want to know how to add components dynamically to a JDialog. I know there is a similar question on SO here, but as you can see, I have his solution as a part of my code.
So the idea is that on click of the button, I need to add a component on the dialog. The sample code is below:
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
Test test = new Test();
test.createDialog();
}
public void createDialog() {
DynamicDialog dialog = new DynamicDialog(this);
dialog.setSize(300, 300);
dialog.setVisible(true);
}
}
class DynamicDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
public DynamicDialog(final JFrame owner) {
super(owner, "Dialog Title", Dialog.DEFAULT_MODALITY_TYPE);
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createRigidArea(new Dimension(3, 10)));
panel.add(createLabel("Click on add"));
panel.add(Box.createRigidArea(new Dimension(23, 10)));
panel.add(createLabel("To add another line of text"));
panel.add(Box.createHorizontalGlue());
mainPanel.add(panel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
JButton button = new JButton();
button.setText("Add another line");
buttonPanel.add(button);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Container contentPane = owner.getContentPane();
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
contentPane.add(_panel);
contentPane.validate();
contentPane.repaint();
owner.pack();
}
});
pack();
setLocationRelativeTo(owner);
this.add(mainPanel);
}
JLabel createLabel(String name) {
JLabel label = new JLabel(name);
return label;
}
}
If you add it to the main panel it will work, you were adding it to the content pane of the frame which it seems it does not show up anywhere.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
mainPanel.add(_panel);
mainPanel.validate();
mainPanel.repaint();
owner.pack();
}
})

Switch Panels in a JFrame

I have 2 JPanels and 1 JFrame, and I'm trying to switch between panels when I click a button..
I don't want to use CardLayout, because I want different panels and with CardLayouts I just can have the same button for both.
My code is:
package javaapplication2;
import javax.swing.JPanel;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
public NewJFrame() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(121, 183, 60));
setSize(200, 300);
setResizable(false);
/**panel1**/
jButton1 = new javax.swing.JButton();
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.setText("jButton1");
panel1.setBackground(new java.awt.Color(121, 183, 60));
panel1.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton1)
.addContainerGap(172, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton1)
.addContainerGap(158, Short.MAX_VALUE))
);
/**panel2**/
jButton2 = new javax.swing.JButton();
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton2.setText("jButton2");
panel2.setBackground(new java.awt.Color(101, 13, 61));
panel2.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout2 = new javax.swing.GroupLayout(panel2);
panel2.setLayout(layout2);
layout2.setHorizontalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton2)
.addContainerGap(172, Short.MAX_VALUE))
);
layout2.setVerticalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton2)
.addContainerGap(158, Short.MAX_VALUE))
);
add(panel2);
pack();
}
public void changePanel(){
getContentPane().removeAll();
add(panel1);
invalidate();
repaint();
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
}
Here is one small example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2(contentPane);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel)
{
contentPane = panel;
setOpaque(true);
setBackground(Color.RED.darker().darker());
//construct components
jcomp4 = new JButton ("openNewWindow");
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add(jcomp4);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
class MyPanel2 extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
public MyPanel2(JPanel panel)
{
contentPane = panel;
setOpaque(true);
setBackground(Color.GREEN.darker().darker());
//construct components
jcomp1 = new JButton ("Back");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
LATEST EDIT
Show JPanel of your choice, inside CardLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private MyPanel2 panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane, this);
panel2 = new MyPanel2(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel2(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp4;
private JPanel contentPane;
private JComboBox choiceBox;
public MyPanel(JPanel panel, CardLayoutExample cle)
{
choiceBox = cle.getChoiceBox();
contentPane = panel;
setOpaque(true);
setBackground(Color.RED.darker().darker());
//construct components
jcomp4 = new JButton ("Show New Panel");
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp4);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
class MyPanel2 extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel2(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}

Categories