Maybe you can help me out here :)
I want to "simulate" like say 10 machine-stations. In my JFrame/Container (I tried both) I put these 10 maschines ( = 10 JPanels containing x buttons, textfields, whatever of my desired design), and I want to have different informations on each one and change them for my needs.
I tried to change the value of a JTextField with an JButton (like setting the priority of the machine + 1. But I cannot distinguish between the 10 "priority up" buttons :(
How you do that? My idea was to speak somehow to the JPanel it came from but I can´t.
Container wizardFrame = new JFrame();
wizardFrame.setLayout(new GridLayout(2,5));
String Name;
for(int i = 1; i < 11; i++){
Name = "Maschine " + i;
fillWizardFrame(wizardFrame, Name, i);
}
wizardFrame.setVisible(true);
}
public void fillWizardFrame(Container wizardFrame, String Name, int i) {
JPanel MaschineId = new JPanel();
MaschineId.setLayout(new BorderLayout());
JTextField maschineName = new JTextField(Name ,10);
MaschineId.add(maschineName, BorderLayout.WEST);
maschinePrioritaet = new JTextField("20",10);
MaschineId.add(maschinePrioritaet,BorderLayout.CENTER);
JButton Higher = new JButton("Higher " + i); Higher.addActionListener(this);
MaschineId.add(Higher, BorderLayout.NORTH);
wizardFrame.add(MaschineId);
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getActionCommand().contains("Higher")){
System.out.println("Higher pressed " + event.getActionCommand());
}
// i tried .getID , .getSource etc... :/
}
I want to change the value of maschinePrioritaet with my "higher" button, but I can´t... This thing took me hours of searching and trying but wasn´t able to find something.
Thank you so much for your help!
Best, Andrea
You have to work more with objects and especially Views (like in MVC). A View represents an object, in this case it looks like some machine (which is a name, an id and a priority). So you need to create a machine panel that is attached to that model.
Here is something closer to that (but there are still many improvements to do):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Wizard {
public Wizard() {
JFrame wizardFrame = new JFrame();
wizardFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wizardFrame.setLayout(new GridLayout(2, 5));
String name;
for (int i = 1; i < 11; i++) {
name = "Maschine " + i;
MashinePanel mashinePanel = new MashinePanel(name, i);
wizardFrame.add(mashinePanel.getPanel());
}
wizardFrame.pack();
wizardFrame.setVisible(true);
}
public static class MashinePanel implements ActionListener {
private final String name;
private final int id;
private JTextField maschineNameTF;
private JFormattedTextField maschinePrioritaetTF;
private JButton higher;
private JPanel machinePanel;
public MashinePanel(String name, int i) {
super();
this.name = name;
this.id = i;
machinePanel = new JPanel();
machinePanel.setLayout(new BorderLayout());
maschineNameTF = new JTextField(name, 10);
machinePanel.add(maschineNameTF, BorderLayout.WEST);
maschinePrioritaetTF = new JFormattedTextField(20);
maschinePrioritaetTF.setColumns(10);
machinePanel.add(maschinePrioritaetTF, BorderLayout.CENTER);
higher = new JButton("Higher " + i);
higher.addActionListener(this);
machinePanel.add(higher, BorderLayout.NORTH);
}
public JPanel getPanel() {
return machinePanel;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().contains("Higher")) {
Object value = maschinePrioritaetTF.getValue();
int priority = 20;
if (value instanceof Integer) {
priority = (Integer) value;
}
maschinePrioritaetTF.setValue(priority + 1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Wizard();
}
});
}
}
Related
how to create jcomboBox with two /multiple columns in the drop down let but when we select only one selected value show in Jcombobox
please give me any solution for this .
You might be able to use JList#setLayoutOrientation(JList.VERTICAL_WRAP):
import java.awt.*;
import javax.accessibility.Accessible;
import javax.swing.*;
import javax.swing.plaf.basic.ComboPopup;
public class TwoColumnsDropdownTest {
private Component makeUI() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("111");
model.addElement("2222");
model.addElement("3");
model.addElement("44444");
model.addElement("55555");
model.addElement("66");
model.addElement("777");
model.addElement("8");
model.addElement("9999");
int rowCount = (model.getSize() + 1) / 2;
JComboBox<String> combo = new JComboBox<String>(model) {
#Override public Dimension getPreferredSize() {
Insets i = getInsets();
Dimension d = super.getPreferredSize();
int w = Math.max(100, d.width);
int h = d.height;
int buttonWidth = 20; // ???
return new Dimension(buttonWidth + w + i.left + i.right, h + i.top + i.bottom);
}
#Override public void updateUI() {
super.updateUI();
setMaximumRowCount(rowCount);
setPrototypeDisplayValue("12345");
Accessible o = getAccessibleContext().getAccessibleChild(0);
if (o instanceof ComboPopup) {
JList<?> list = ((ComboPopup) o).getList();
list.setLayoutOrientation(JList.VERTICAL_WRAP);
list.setVisibleRowCount(rowCount);
list.setFixedCellWidth((getPreferredSize().width - 2) / 2);
}
}
};
JPanel p = new JPanel();
p.add(combo);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TwoColumnsDropdownTest().makeUI());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
You need to do a few things.
By default, what is displayed in the JComboBox, as the selected item, is the value returned by method toString of the items in the ComboBoxModel. Based on your comment I wrote an Item class and overrode the toString method.
In order to display something different in the drop-down list, you need a custom ListCellRenderer.
In order for the drop-down list to display the entire details of each item, the drop-down list needs to be wider than the JComboBox. I used code from the following SO question to achieve that:
How can I change the width of a JComboBox dropdown list?
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;
public class MultiColumnCombo implements PopupMenuListener {
private JComboBox<Item> combo;
public void popupMenuCanceled(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
EventQueue.invokeLater(() -> {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
JScrollPane scrollPane = (JScrollPane) comboPopup.getComponent(0);
Dimension d = setCurrentDimension(scrollPane.getPreferredSize());
scrollPane.setPreferredSize(d);
scrollPane.setMaximumSize(d);
scrollPane.setMinimumSize(d);
scrollPane.setSize(d);
Point location = combo.getLocationOnScreen();
int height = combo.getPreferredSize().height;
comboPopup.setLocation(location.x, location.y + height - 1);
comboPopup.setLocation(location.x, location.y + height);
});
}
}
}
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createCombo());
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createCombo() {
JPanel panel = new JPanel();
Item[] items = new Item[]{new Item("A", "Item A", new BigDecimal(1.99d), new BigDecimal(2.99d)),
new Item("B", "Item B", new BigDecimal(7.5d), new BigDecimal(9.0d)),
new Item("C", "Item C", new BigDecimal(0.25d), new BigDecimal(3.15d))};
combo = new JComboBox<>(items);
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
comboPopup.getList().setCellRenderer(new MultiColumnRenderer());
}
}
combo.addPopupMenuListener(this);
panel.add(combo);
return panel;
}
private Dimension setCurrentDimension(Dimension dim) {
Dimension d = new Dimension(dim);
d.width = 120;
return d;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MultiColumnCombo().createAndDisplayGui());
}
}
class Item {
private String code;
private String name;
private BigDecimal price;
private BigDecimal salePrice;
public Item(String code, String name, BigDecimal price, BigDecimal salePrice) {
this.code = code;
this.name = name;
this.price = price;
this.salePrice = salePrice;
}
public String displayString() {
return String.format("%s %s %s %s",
code,
name,
NumberFormat.getCurrencyInstance().format(price),
NumberFormat.getCurrencyInstance().format(salePrice));
}
public String toString() {
return name;
}
}
class MultiColumnRenderer implements ListCellRenderer<Object> {
/** Component returned by method {#link #getListCellRendererComponent}. */
private JLabel cmpt;
public MultiColumnRenderer() {
cmpt = new JLabel();
cmpt.setOpaque(true);
cmpt.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
public Component getListCellRendererComponent(JList<? extends Object> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
String text;
if (value == null) {
text = "";
}
else {
if (value instanceof Item) {
text = ((Item) value).displayString();
}
else {
text = value.toString();
}
}
cmpt.setText(text);
if (isSelected) {
cmpt.setBackground(list.getSelectionBackground());
cmpt.setForeground(list.getSelectionForeground());
}
else {
cmpt.setBackground(list.getBackground());
cmpt.setForeground(list.getForeground());
}
cmpt.setFont(list.getFont());
return cmpt;
}
}
I've some issues with my code for studies, it's our first time with Java and I don't know how to change the icon of JRadioButtons contents in an array.
package exo_02_01;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
#SuppressWarnings("serial")
public class ControleEtiquette extends JToolBar {
private ImageIcon[] m_iconesBoutons = new ImageIcon[18];
private JRadioButton[] m_boutons = new JRadioButton[6];
private String m_nomsIcones[] = { "bhgauche", "bhcentre", "bhdroite", "bvhaut", "bvcentre", "bvbas" };
private static final int NUMBER_BUTTONS = 6;
public ControleEtiquette() {
super();
chargerIcones();
creerBoutons();
}
private void chargerIcones() {
for (int i = 0; i < NUMBER_BUTTONS; i++) {
m_iconesBoutons[i] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + ".gif");
m_iconesBoutons[i + NUMBER_BUTTONS] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "R.gif");
m_iconesBoutons[i + NUMBER_BUTTONS * 2] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "B.gif");
}
}
private void creerBoutons() {
for (int i = 0; i < m_boutons.length; ++i) {
m_boutons[i] = new JRadioButton(m_iconesBoutons[i]);
add(m_boutons[i]);
m_boutons[i].addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e)
{
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[0]);
}
public void mouseClicked(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[NUMBER_BUTTONS * 2 - 1]);
}
public void mouseExited(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[5]);
}
});
if (i == 2)
addSeparator();
}
}
My code in my chargerBoutons() method work well, but my aim is to set the icon according to the current button. I tried to do like
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[i]);
But i is undefined in this scope.
How can I fix it ?
Thanks
Actually, I think you set the icon correctly, but you have to ask for an update of the UI...
So add the call updateUI() at the end of your creerBoutonsmethod. (it apply on the toolbar (ie: your object).
see JToolbar
I am pretty new to Java. This is my class homework. I finished everything except the JFrame color doesn't show. I looked at all the other similar questions. Most of them said to use getContentPane(). The problem is I added that already but it is not showing. Below is my code. I separated it into two parts. The second part has all those JFrame.getContentPane().setBackground(color.**) code. Thank you.
import java.awt.BorderLayout;
import java.awt.Color;
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.JTextField;
public class NumberGame extends JFrame {
private JPanel Content;
private JFrame DisplayFrame;
private JTextField Input;
private JLabel DisplayText, Message;
private int Guess;
private JButton button;
private JButton NewGame;
private int Number;
private int Lowest = 0;
private int Highest = 0;
public void NumberGame () {
Content = new JPanel ();
DisplayFrame = new JFrame ("Welcome");
DisplayFrame.setSize(700, 400);
DisplayFrame.setLayout (new BorderLayout());
DisplayText = new JLabel ("I have a number between 1 and 1000. Can you guess my number?
Enter your first guess.");
Input = new JTextField (20);
Content.add(Input);
Message = new JLabel ("");
button = new JButton ("Submit");
button.addActionListener (new GuessHandler());
NewGame = new JButton ("New Game");
NewGame.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent ae) {
Input.setText("");
Message.setText("");
repaint();
}
} );
DisplayFrame.add(Content);
Content.add(DisplayText);
Content.add(Input);
Content.add(button);
Content.add(NewGame);
Content.add(Message);
theGame();
DisplayFrame.setVisible(true);
}
public void theGame () {
Number = (int) (Math.random() * 1000 +1);
}
public static void main(String[] args) {
NumberGame a = new NumberGame ();
a.NumberGame();
}
Here is the rest of the code that I have problem with.
class GuessHandler implements ActionListener {
#Override
public void actionPerformed (ActionEvent ae) {
Guess = Integer.parseInt(Input.getText());
if(Guess>Number) {
Message.setText("Too high!");
if (Guess < Lowest) {
Lowest = Guess;
DisplayFrame.getContentPane().setBackground(Color.red);
}
else
DisplayFrame.getContentPane().setBackground(Color.blue);
}
else if (Guess < Number) {
Message.setText("Too Low!");
if (Guess > Highest) {
Highest = Guess;
DisplayFrame.getContentPane().setBackground(Color.red);
}
else
DisplayFrame.getContentPane().setBackground(Color.blue);
}
else {
Message.setText("Correct!");
Input.setEditable(false);
Lowest = 0;
Highest = 1000;
}
repaint ();
}
}
}
Content is a JPanel, because JFrame uses a BorderLayout, the panel Content will occupy the entire available space, covering the frames own content pane (don't confuse the two, the are different).
Try changing
DisplayFrame.add(Content);
to
DisplayFrame.setContentPane(Content);
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
I have a Gridlayout filled with images loaded from File and I want to add a different, for example, popup, on mouseEvent mouseClicked for each image. How do I determine which image I'm clicking? I've tried adding GetComponentAt(Point), but Eclipse keeps showing that as an unidentified method for the mouseAdapter, and how do I determine the fields for the if statement?
This is what I have:
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
public void testclass (Container window){
JPanel index = new JPanel();
String index2[] = {title};
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
File folder = new File("images/");
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = "images/" + listOfFiles[i].getName();
final ImageIcon images = new ImageIcon(nr);
final JLabel display[] = new JLabel[1];
for (int n = 0; n < 1; n++){
display[n] = new JLabel(images);
panel.add(display[n]);
} }
panel.addMouseListener(new MouseAdapter()
{ public void mouseClicked (MouseEvent e)
{ //JPanel panel = (JPanel) getComponentAt(e.getPoint());
JOptionPane.showMessageDialog(null, "Message");
}});
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(index, BorderLayout.PAGE_START);
window.add(template, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent event){
CardLayout change = (CardLayout)(template.getLayout());
change.show(template, (String)event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e){
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
Edit: Proper Answer
Thankyou for providing code. I have adjusted some things so hopefully you can understand them.
Firstly I have added a new object, ImageButton. From when I added the actionListener the functionality you wanted was already done (minus the good looks, you will have to play around with that, or ask another question)
Added a 'dir' string so that you don't have to keep copy and pasting the directory address.
I had to adjust the size of the window through the userInterface() method, you should look at being able to shorten the sequence of being able to adjust the parameters, maybe another GUI object to keep all that information together.
A couple of things:
The code you wrote was good but it would need for you to adjust alot of (getting the size of windows and repeatedly check for different sizes if you adjusted the window size where a mouse click could click on other image that you don't want!) in order for a mouseListener to work, I am guessing with a wide range of images you would be providing.
Putting comments in your code can help both you and someone trying to help you.
Anyways, please upvote/accept answer if this helps out, which I'm sure it does.
Good Luck!
Put these files into your eclipse and run them it should work if you adjust the dir string to follow your original directory path.
testclass.java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
final String dir = "images/";
public void testclass(Container window) {
JPanel index = new JPanel();
String[] index2 = { title };
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
index.setSize(500, 500);
File folder = new File(dir);
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = dir + listOfFiles[i].getName();
panel.add(new ImageButton(nr));
}
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(template, BorderLayout.CENTER);
window.add(index, BorderLayout.NORTH);
window.setVisible(true);
}
public void itemStateChanged(ItemEvent event) {
CardLayout change = (CardLayout) (template.getLayout());
change.show(template, (String) event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
showwindow.setSize(500, 500);
}
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
ImageButton.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class ImageButton extends JButton {
private String fileName;
private ImageIcon image;
private JButton button;
public ImageButton(String fileName) {
setFileName(fileName);
setImage(new ImageIcon(fileName));
setButton(new JButton(getImage()));
this.setIcon(getImage());
this.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, ae.getSource());
}
});
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ImageIcon getImage() {
return image;
}
public void setImage(ImageIcon image) {
this.image = image;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
}
In my GUI, after importing an Excel file, I need to create a variable amount of panels/tabs. The amount depends on the number of rows imported from the Excel file. I need to show the information contained in row in a different panel, with a couple of buttons to move between all the tabs. For example, if the Excel file contains 6 rows:
Field1: user1
Field2: user1Age
< [1/6] >
So, I can move through the different panels, by clicking on the arrows:
Field1: user2
Field2: user2Age
< [2/6] >
One more consideration: Excel file import is not the only way to get information, it must be possible to manually add information. Therefore, after starting the GUI there must be at least one panel, and if the user decides to import an Excel file, then multiple panels must be created.
I need just a hint to start coding. And of course I am open to other possibilities.
Here is a sample code that should get you started (you will need to reorganize a bit the code). Although there are 1000 dummy users, it only uses a single panel to display the information:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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 TestMultiplePanels {
private final UserList userList;
private User currentUser;
private JTextField name;
private JTextField age;
private JTextField index;
private JButton prev;
private JButton next;
public TestMultiplePanels(UserList userList) {
this.userList = userList;
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel userPanel = new JPanel(new BorderLayout());
JPanel userInfoPanel = new JPanel(new GridBagLayout());
JPanel buttonPanel = new JPanel(new FlowLayout());
JLabel nameLabel = new JLabel("Name");
JLabel ageLabel = new JLabel("Age");
name = new JTextField(30);
age = new JTextField(5);
index = new JTextField(5);
index.setEditable(false);
prev = new JButton("<");
prev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.previous(currentUser));
}
});
next = new JButton(">");
next.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.next(currentUser));
}
});
GridBagConstraints gbcLabel = new GridBagConstraints();
gbcLabel.anchor = GridBagConstraints.EAST;
GridBagConstraints gbcField = new GridBagConstraints();
gbcField.anchor = GridBagConstraints.WEST;
gbcField.gridwidth = GridBagConstraints.REMAINDER;
userInfoPanel.add(nameLabel, gbcLabel);
userInfoPanel.add(name, gbcField);
userInfoPanel.add(ageLabel, gbcLabel);
userInfoPanel.add(age, gbcField);
buttonPanel.add(prev);
buttonPanel.add(index);
buttonPanel.add(next);
userPanel.add(userInfoPanel);
userPanel.add(buttonPanel, BorderLayout.SOUTH);
setCurrentUser(userList.getUsers().get(0));
frame.add(userPanel);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
frame.setVisible(true);
}
private void setCurrentUser(User user) {
currentUser = user;
name.setText(user.getUserName());
age.setText(String.valueOf(user.getAge()));
index.setText(user.getIndex() + "/" + userList.getCount());
next.setEnabled(userList.hasNext(user));
prev.setEnabled(userList.hasPrevious(user));
}
public static class UserList {
private List<User> users;
private List<User> unmodifiableUsers;
public UserList() {
super();
this.users = load();
unmodifiableUsers = Collections.unmodifiableList(users);
}
public int getCount() {
return users.size();
}
public List<User> getUsers() {
return unmodifiableUsers;
}
private List<User> load() {
List<User> users = new ArrayList<TestMultiplePanels.User>();
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setUserName("User " + (i + 1));
user.setAge((int) (Math.random() * 80));
user.setIndex(i + 1);
users.add(user);
}
return users;
}
public boolean hasNext(User user) {
return user.getIndex() - 1 < users.size();
}
public boolean hasPrevious(User user) {
return user.getIndex() > 1;
}
public User next(User user) {
if (hasNext(user)) {
return users.get(user.getIndex());
} else {
return null;
}
}
public User previous(User user) {
if (hasPrevious(user)) {
return users.get(user.getIndex() - 2);
} else {
return null;
}
}
}
public static class User {
private String userName;
private int age;
private int index;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
public static void main(String[] args) {
final UserList userList = new UserList();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestMultiplePanels testMultiplePanels = new TestMultiplePanels(userList);
testMultiplePanels.initUI();
}
});
}
}
You can create the panels dynamically using an ArrayList, which I think is flexible enough for that and easily manageable. To handle panels display, you can use a CardLayout. Hope it helps
ArrayList<JPanel> panelGroup = new ArrayList<JPanel>();
for (int i=0;i<numberOfPanelsToCreate;i++){
panelGroup.add(new JPanel());
}