JPanel of main does not get updated from another class - java

I have class Home that extends JFrame, it holds a static variable panel_event. I have another class called EventLabel, which created a label and it's functions and adds it to the panel using refresh() method, code runs with no error, but my panel_event content does not get updated "show"
I have already added revalidate(), and repaint() methods
public EventLabel(String name2, String date2, int priority2, String note2) {
super();
this.name = name2;
this.date = date2;
this.priority = priority2;
this.note = note2;
}
public void buildLabel() {
label = new JLabel(this.getName());
label.setBounds(10, 11, 403, 34);
label.setForeground(Color.WHITE);
label.setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
String n = this.getNote();
String d = this.getDate();
int p = this.getPriority();
String na = this.getName();
setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
EventDetailFrame detailFrame = new EventDetailFrame();
detailFrame.NewWindow();
detailFrame.textAreaNoteD.setText(n);
detailFrame.textFieldNameD.setText(na);
detailFrame.textFieldDateD.setText(d);
detailFrame.textFieldPriorityD.setText("Priority");
}
});
}
public void refresh(){
panel_event.add(label);
panel_event.revalidate();
panel_event.repaint();
}
This is the frame with button that is suppose to change content of panel_event
btnSaveAndClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = txtEventName.getText();
String date = txtEventDate.getText();
String note = txtEventNote.getText();
int priority = getPriorityNumber(txtEventPriority.getText());
Event event = new Event(name, date, note, priority);
EventLabel event_label = new EventLabel(event.getName(),event.getDate(),event.getPriority(),event.getNote());
event_label.buildLabel();
event_label.refresh();
dispose();
}
});
After clicking btnSaveAndClose, I expected the panel_event to show my new JLabel

I created a working example on how to show new label. You can call validate() and repaint().
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.StringJoiner;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class EventLabel extends JLabel
{
private static final long serialVersionUID = -3122247523298894551L;
public EventLabel(String name, String date, String priority, String note)
{
super(name);
setBorder(BorderFactory.createLineBorder(Color.WHITE, 3, false));
setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
this.setOpaque(true);
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e)
{
StringJoiner text = new StringJoiner("\n");
text.add("name: " + name);
text.add("date: " + date);
text.add("priority: " + priority);
text.add("note: " + note);
JOptionPane.showMessageDialog(null, text, "Event", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
AND
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main
{
private static JButton button;
private static JPanel labelPanel;
private static JTextField nameField;
private static JTextField dateField;
private static JTextField priorityField;
private static JTextField noteField;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
JFrame window = new JFrame();
window.setResizable(false);
window.setTitle("Label Test");
window.getContentPane().add(getContent());
initController();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(680, 700);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
});
}
protected static void initController()
{
button.addActionListener(event -> {
labelPanel.add(new EventLabel(nameField.getText(), dateField.getText(), priorityField.getText(),
noteField.getText()));
nameField.setText("");
dateField.setText("");
priorityField.setText("");
noteField.setText("");
labelPanel.validate();
labelPanel.repaint();
});
}
private static Component getContent()
{
JPanel panel = new JPanel(new BorderLayout());
panel.add(getNorthPanel(), BorderLayout.NORTH);
labelPanel = new JPanel(new FlowLayout());
labelPanel.setBorder(BorderFactory.createTitledBorder("Events"));
panel.add(labelPanel, BorderLayout.CENTER);
return panel;
}
private static Component getNorthPanel()
{
JPanel panel = new JPanel(new FlowLayout());
JPanel inputPanel = new JPanel(new GridLayout(0, 2));
inputPanel.setPreferredSize(new Dimension(400, 100));
nameField = new JTextField();
dateField = new JTextField();
priorityField = new JTextField();
noteField = new JTextField();
inputPanel.add(new JLabel("name"));
inputPanel.add(nameField);
inputPanel.add(new JLabel("date"));
inputPanel.add(dateField);
inputPanel.add(new JLabel("priority"));
inputPanel.add(priorityField);
inputPanel.add(new JLabel("note"));
inputPanel.add(noteField);
panel.add(inputPanel);
button = new JButton("add event");
panel.add(button);
return panel;
}
}

Related

GUI: setSize() method of second window does not work

I have 2 windows at the moment. After a user clicks on the Submit button, the Main window appears but it appears as such:
The codes are:
LoginForm.java
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm extends JFrame{
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm()
{
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2,2));
loginArea.add(loginEmail); //add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); //add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1,2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler= new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == submit)
{
dispose();
new Main().setVisible(true);
}
}
}
}
And Main.java:
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame{
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main()
{
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1,3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1,3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
The testMain.java:
package interfaceGUI;
import javax.swing.JFrame;
public class testMain {
public static void main(String[] args) {
Main myFrame = new Main();
myFrame.setSize(300,200); //not working
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Can anybody suggest me what's wrong? Thanks.
I wouldn't call setSize() but rather would let my components and the layout managers set their own sizes by calling pack(). Occasionally you might want to override a component's getPreferredSize() but if you do so, do it with extreme care.
Calling pack() does seem to work for me with your code:
import java.awt.FlowLayout;
import java.awt.GridLayout;
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;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMain {
private static void createAndShowGui() {
LoginForm loginForm = new LoginForm();
loginForm.pack();
loginForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class LoginForm extends JFrame {
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm() {
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2, 2));
loginArea.add(loginEmail); // add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); // add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1, 2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == submit) {
dispose();
Main main = new Main();
main.pack();
main.setVisible(true);
}
}
}
}
class Main extends JFrame {
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main() {
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1, 3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1, 3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
Note that if this were my project, I'd change it to use a CardLayout to swap views, something like:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestMain2 extends JPanel {
private static final String GUI_NAME = "My GUI";
private CardLayout cardLayout = new CardLayout();
private LoginPanel loginPanel = new LoginPanel();
private HomePanel homePanel = new HomePanel();
public TestMain2() {
setLayout(cardLayout);
add(loginPanel, LoginPanel.NAME);
add(homePanel, HomePanel.NAME);
for (PartyCategory partyCategory : PartyCategory.values()) {
PartyPanel partyPanel = new PartyPanel(partyCategory.getName());
partyPanel.addPropertyChangeListener(PartyPanel.RETURN, new PartyPanelListener());
add(partyPanel, partyCategory.getName());
}
loginPanel.addPropertyChangeListener(LoginPanel.NAME, new LoginPanelListener());
homePanel.addPropertyChangeListener(HomePanel.PARTY_CATEGORY, new HomeListener());
}
private class LoginPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
System.out.println("Submit Pressed");
System.out.println("Login: " + loginPanel.getLogin());
// TODO: Dangerous code!!! Delete this!!!
System.out.println("Password: " + new String(loginPanel.getPassword()));
cardLayout.show(TestMain2.this, HomePanel.NAME);
} else {
System.out.println("Cancel Pressed");
}
}
}
private class HomeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
PartyCategory partyCategory = (PartyCategory) evt.getNewValue();
cardLayout.show(TestMain2.this, partyCategory.getName());
}
}
private class PartyPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
cardLayout.show(TestMain2.this, HomePanel.NAME);
}
}
}
private static void createAndShowGui() {
TestMain2 mainPanel = new TestMain2();
JFrame frame = new JFrame(GUI_NAME);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings({"serial", "hiding"})
class LoginPanel extends JPanel {
public static final String NAME = "Login";
private static final int COLS = 10;
private static final String EMAIL_PROMPT = "Enter Your Email Address:";
private static final String PASSWORD_PROMPT = "Enter Your Password:";
private boolean submitPressed = false;
private JTextField textField = new JTextField(COLS);
private JPasswordField passField = new JPasswordField(COLS);
public LoginPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
buttonPanel.add(new JButton(new ButtonAction("Submit", KeyEvent.VK_S, true)));
buttonPanel.add(new JButton(new ButtonAction("Cancel", KeyEvent.VK_C, false)));
buttonPanel.add(new JButton(new ExitAction()));
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setBorder(BorderFactory.createTitledBorder(NAME));
innerPanel.add(new JLabel(EMAIL_PROMPT, JLabel.LEADING), getGbc(0, 0));
innerPanel.add(textField, getGbc(1, 0));
innerPanel.add(new JLabel(PASSWORD_PROMPT, JLabel.LEADING), getGbc(0, 1));
innerPanel.add(passField, getGbc(1, 1));
innerPanel.add(buttonPanel, getGbc(0, 2, 2, 1));
add(innerPanel);
}
public boolean isLoginValid() {
return submitPressed;
}
public void setSubmitPressed(boolean submitPressed) {
this.submitPressed = submitPressed;
firePropertyChange(NAME, null, submitPressed);
}
public String getLogin() {
return textField.getText();
}
public char[] getPassword() {
return passField.getPassword();
}
private class ButtonAction extends AbstractAction {
private boolean submitPressed;
public ButtonAction(String name, int mnemonic, boolean submitPressed) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.submitPressed = submitPressed;
}
#Override
public void actionPerformed(ActionEvent e) {
setSubmitPressed(submitPressed);
}
}
private static GridBagConstraints getGbc(int x, int y, int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (x == 1) {
gbc.insets = new Insets(5, 15, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.EAST;
} else {
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
}
return gbc;
}
private static GridBagConstraints getGbc(int x, int y) {
return getGbc(x, y, 1, 1);
}
}
#SuppressWarnings({"serial", "hiding"})
class HomePanel extends JPanel {
public static final String NAME = "Home";
public static final String PARTY_CATEGORY = "Party Category";
private static final String PROMPT = "Choose Party Category:";
private PartyCategory partyCategory = null;
public HomePanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
for (PartyCategory partyCategory : PartyCategory.values()) {
buttonPanel.add(new JButton(new ButtonListener(partyCategory)));
}
add(new JLabel(PROMPT));
add(buttonPanel);
}
public PartyCategory getPartyCategory() {
return partyCategory;
}
public void setPartyCategory(PartyCategory partyCategory) {
this.partyCategory = partyCategory;
firePropertyChange(PARTY_CATEGORY, null, partyCategory);
}
private class ButtonListener extends AbstractAction {
private PartyCategory partyCategory;
public ButtonListener(PartyCategory partyCategory) {
super(partyCategory.getName());
this.partyCategory = partyCategory;
int mnemonic = partyCategory.getName().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
setPartyCategory(partyCategory);
}
}
}
enum PartyCategory {
BIRTHDAY_PARTY("Birthday Party"),
SUMMER_FESTIVE_PARTY("Summer/Festive Party"),
HALLOWEEN_PARTY("Halloween Party");
private String name;
private PartyCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressWarnings("serial")
class PartyPanel extends JPanel {
public static final String RETURN = "return";
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public PartyPanel(String name) {
JLabel label = new JLabel(name, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));
JPanel returnButtonPanel = new JPanel();
returnButtonPanel.add(new JButton(new ReturnAction()));
returnButtonPanel.add(new JButton(new ExitAction()));
setLayout(new BorderLayout());
add(label);
add(returnButtonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class ReturnAction extends AbstractAction {
public ReturnAction() {
super("Return Home");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
PartyPanel.this.firePropertyChange(RETURN, null, true);
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
// this will not work for JMenuItem which would require a test to see if coming
// from a pop up first.
Component source = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(source);
win.dispose();
}
}

How to pass value JList item from JFrame into another JFrame (just value)?

I have write a test with two class.
The first JPanel, Gestion: JFrame with jlist + button (the button open the Jlist 2, PanelTest)
The second JPanel, PanelTest: JFrame and I want to recover in String, the select value item in the JFrame Gestion (JList)
How to do that ?
Gestion.java:
package IHM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JList;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
public class Gestion extends JFrame {
private DocumentListener myListener;
public String test;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public String getTest() {
return test;
}
/**
* Create the frame.
* #throws Exception
*/
public Gestion() throws Exception {
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);
final PanelTest panel2 = new PanelTest();
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
String choix[] = {" Pierre", " Paul", " Jacques", " Lou", " Marie"};
final JList list = new JList(choix);
panel.add(list);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
test = (String) list.getSelectedValue();
System.out.println(test);
// PanelTest.setValue(test);
}
});
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PanelTest().setVisible(true);
fermerFenetre();
}
});
panel_1.add(btnNewButton);
}
public void fermerFenetre(){
this.setVisible(false);
}
}
PanelTest.java
package IHM;
import java.awt.BorderLayout;
public class PanelTest extends JFrame {
public String tyty;
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PanelTest frame = new PanelTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PanelTest() {
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);
textField = new JTextField();
contentPane.add(textField, BorderLayout.WEST);
textField.setColumns(10);
}
}
Suggestions:
Make your list variable a field, not a local variable, or else make it a final local variable so that it is accessible inside of the anonymous ActionListener.
Obtain the selected list item in your ActionListener where you launch the 2nd window.
Pass that String into your PanelTest object via a String parameter.
The second window should be a dialog such as a JDialog, not a JFrame.
As an aside, you'll rarely want to have your GUI classes extend top level windows such as JFrames or JDialogs as that greatly limits the flexibility of your GUI code.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Gestion2 extends JPanel {
private static final String CHOIX[] = { " Pierre", " Paul", " Jacques",
" Lou", " Marie" };
private JList<String> choixList = new JList<>(CHOIX);
public Gestion2() {
JPanel listPanel = new JPanel();
listPanel.add(new JScrollPane(choixList));
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new ListSelectAction("Select Item and Press")));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(listPanel);
add(btnPanel);
}
private class ListSelectAction extends AbstractAction {
public ListSelectAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = choixList.getSelectedValue();
if (selectedItem != null) {
PanelTest2 panelTest2 = new PanelTest2(selectedItem);
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
// JOptionPane example
JOptionPane.showMessageDialog(win, panelTest2,
"JOptionPane Example", JOptionPane.PLAIN_MESSAGE);
// or JDialog example
JDialog dialog = new JDialog(win, "JDialog Example",
ModalityType.APPLICATION_MODAL);
dialog.add(panelTest2);
dialog.pack();
dialog.setLocationRelativeTo(win);
dialog.setVisible(true);
}
}
}
private static void createAndShowGui() {
Gestion2 mainPanel = new Gestion2();
JFrame frame = new JFrame("Gestion2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PanelTest2 extends JPanel {
private String selectedItem;
private JTextField textField = new JTextField(10);
public PanelTest2(String selectedItem) {
this.selectedItem = selectedItem;
textField.setText(selectedItem);
add(new JLabel("Selected Item:"));
add(textField);
}
public String getSelectedItem() {
return selectedItem;
}
}

JTextArea not show

I create an Team application in java. I add a logo which is the combination of Rectangle and Circle in JFrame but after add logo in application JTextArea not shown... Also adding new player not shown...
Here is my code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MainGUI extends JFrame
{
private JLabel teamName;
private JLabel playerCount;
private JLabel maxPlayer;
private JButton createTeam;
private JButton addOnePlayer;
private JButton addRemining;
private JButton exit;
private Team team;
private boolean teamCreated;
private JTextArea text;
Logo logo;
public static void main(String[] args)
{
new MainGUI();
}
public MainGUI()
{
super.setTitle("Team manager");
super.setSize(500,400);
super.setLocation(150,150);
super.setLayout(new BorderLayout());
add(addTopPanel(), BorderLayout.NORTH);
add(textArea(), BorderLayout.CENTER);
add(buttonPanel(), BorderLayout.SOUTH);
Logo logo = new Logo();
logo.setBounds(100, 100, 150,150);
getContentPane().add(logo);
// logo.addSquare(10, 10, 100, 100);
super.setVisible(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel buttonPanel()
{
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2));
createTeam = new JButton("Create Team");
addOnePlayer = new JButton("Add one player");
addRemining = new JButton("Add remaining players");
exit = new JButton("Exit");
buttonPanel.add(createTeam);
buttonPanel.add(addOnePlayer);
buttonPanel.add(addRemining);
buttonPanel.add(exit);
createTeam.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(!teamCreated)
{
teamCreated = true;
team = new Team();
teamName.setText("Team name: "+team.getName());
playerCount.setText("Players count: "+team.getCount());
maxPlayer.setText("Max team size: "+team.getSize());
}
else
{
JOptionPane.showMessageDialog(null,"The team has been already created, and no further Team instances are instantiated");
}
}
});
addOnePlayer.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(team != null)
{
Player pl = Team.createPlayer();
team.addPlayer(pl);
playerCount.setText("Players count: "+team.getCount());
text.setText(team.toString());
}
else
{
JOptionPane.showMessageDialog(null,"Create a team first ");
}
}
});
addRemining.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(team != null)
{
team.addPlayers();
playerCount.setText("Players count: "+team.getCount());
text.setText(team.toString());
}
else
{
JOptionPane.showMessageDialog(null,"Create a team first ");
}
}
});
exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
return buttonPanel;
}
private JTextArea textArea()
{
text = new JTextArea();
return text;
}
private JPanel addTopPanel()
{
JPanel top = new JPanel();
top.setLayout(new GridLayout(1,3));
teamName = new JLabel("Team name: ");
playerCount = new JLabel("Players count: ");
maxPlayer = new JLabel("Max team size: ");
top.add(teamName);
top.add(playerCount);
top.add(maxPlayer);
return top;
}
class Logo extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.drawRect(350,80,70,70);
g.setColor(Color.blue);
g.drawRoundRect(360, 30, 50, 50, 50, 50);;
}
}
}
after add logo in application JTextArea not shown
Reason is this Line:
logo.setBounds(100, 100, 150,150);
getContentPane().add(logo);
setBounds wont work with the layouts of Swing components. So when you are adding the logo in container of JFrame it is adding it to the center , hiding out the JTextArea added in center.

JLabel alignment issues

So, I have a problem. I have a JPanel(BoxLayout, Y_AXIS). In it, I have JLabel, and JTextArea. JTextArea expands freely as I fill it with text, expanding the JPanel with it.
JLabel expands to. That is okay as long the text is vertically aligned to the top. But that command doesn't work for some reason (setVerticalTextPosition, setVerticalAlignment, setAlignmentX). I think the first one is acctually a bug within Java.
Since that didn't work, I tried glueing JLabel to the top border.
I have also set all three setXXSize to sam value to keep the size of JLabel constant.
But it just wont stick, depending on the layout it either snaps to the center or just fills the whole JPanel.
Now, I don't care how, but all I need is a couple of letters that are top-aligned in the space occupied with JLabel (I can even use another JTextComponent, if it will make any difference). Is there a way to do that?
I'd provide you with code, but it's pretty much what I have written above, and since the JPanel is a part of more complex GUI, I'd really have to give you the whole code...
(Which I will, if it will be needed.)
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 150)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 150)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum+".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
questionArea.add(question);
add(questionArea);
page.add(this, index);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
#SuppressWarnings("unused")
Page p = new Page(workspace, 1);
Heading g = new Heading(true, p);
Question q = new Question(p, 1, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
This is the best I can do, refer to Question class for issue.
To get GUI drawn, run it, pres ctrl+n, and then enter.
As I understood you want to achieve this:
If that is true, all you have to do is this:
numberArea.setLayout(new BorderLayout());
and
numberArea.add(number,BorderLayout.NORTH);
As brano88 suggests, change layout manager...
public Question(Page page, int pageNum, int index) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new GridBagLayout());
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum + ".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(numberArea, gbc);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(question, gbc);
add(questionArea);
page.add(this, index);
}

how to change UI depending on combo box selection

In dialog I need to display one group of controls if some combo is checked and another group of controls otherwise.
I.e. I need 2 layers and I need to switch between them when combo is checked/unchecked. How can I do that?
Thanks
CardLayout works well for this, as suggested below.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/6432170 */
public class CardPanel extends JPanel {
private static final Random random = new Random();
private static final JPanel cards = new JPanel(new CardLayout());
private static final JComboBox combo = new JComboBox();
private final String name;
public CardPanel(String name) {
this.name = name;
this.setPreferredSize(new Dimension(320, 240));
this.setBackground(new Color(random.nextInt()));
this.add(new JLabel(name));
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 9; i++) {
CardPanel p = new CardPanel("Panel " + String.valueOf(i));
combo.addItem(p);
cards.add(p, p.toString());
}
JPanel control = new JPanel();
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
});
control.add(combo);
f.add(cards, BorderLayout.CENTER);
f.add(control, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Categories