I have been creating a system by which I am listing various seats on a train within a GUI. I had decided to use a simple grid layout with numbered JButtons representing the seats and the seatNo and empty JLabels to represent empty space (I realise this may be trivial but it was simple). I have used a Gridlayout and I have created the Buttons and Labels as shown below.
I have an List (compArray2) in a separate class that consists of 0s and 1s and a direction that represent where there should be a seat and where the shouldn't be a seat. the .getNum gets the value either 0 for empty space or 1 for a seat and the .getDir gets the direction the seat will be facing.
public JPanel rowPanelCreation(int type, int rowNo, int width){
theNoOfSeats=0;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,width));
List<seatLayout> layout = new ArrayList<>();
layout = ModelConstants.compArray2;
for (seatLayout isit : x2){
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
if (isit.getNum()==0){
if (isit.getDir()=='x'){
panel.add(buttonDis);
}
}
else if (isit.getNum()==1){
theNoOfSeats++;
if (isit.getDir()=='N'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='E'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
panel.add(buttonEna);
}
else if (isit.getDir()=='S'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='W'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
}
}
return panel;
}
the main problem I am having is that when I press one of the seat buttons I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo. Is there a better way I could do this ? I'm assuming that as all the buttons are fundamentally the same, there is no way to differentiate between them ?
"I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo."
Here's your problem. It's a reference problem. In the end, all the buttons will have the same JButton and JLabel reference. So all the buttons and labels will get the last button and label reference created, hence "displays the very last seatNo."
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
You need to create a new JButton and new JLabel reference each iteration
JBUtton buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
JLabel buttonDis = new JLabel();
Another approach would be to have an array of JButton, loop to set the buttons, and add them to the Panel. Say you have a GridLayout(2, 2). You then would need a array of 4 JButtons
JButton[] buttons = new JButton[9];
...
for (int i = 0; i < 4; i++){
buttons[i] = new JButton();
buttons[i].setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
// set other properties for button
panel.add(buttons[i]);
}
Related
I am attempting to design a panel with MiGFormat that has a label at the top, and two buttons at the bottom - a yes/no prompt.
I achieve this closely, but the label yesOrNoText (text is "TEST") is not fully centered:
I initialize the panel containing this prompt like so:
private JPanel createYesNoPrompt() {
JPanel panel = new JPanel(new MigLayout());
panel.setBorder(BorderFactory.createLineBorder(Color.red));
JButton yesButton = new JButton("Yes");
JButton noButton = new JButton("No");
yesOrNoText = new JLabel();
yesOrNoText.setText("TEST");
yesOrNoText.setFont(panel.getFont().deriveFont(Font.BOLD, 30f));
yesOrNoText.setHorizontalAlignment(SwingConstants.CENTER);
Dimension dimension = new Dimension(500, 125);
Font font = panel.getFont().deriveFont(Font.BOLD, 20f);
yesButton.setFont(font);
yesButton.setBackground(new Color(35, 138, 35));
yesButton.setPreferredSize(dimension);
noButton.setFont(font);
noButton.setBackground(new Color(183, 19, 19));
noButton.setPreferredSize(dimension);
yesButton.addActionListener(e -> isYes = true);
noButton.addActionListener(e -> isYes = false);
panel.add(yesOrNoText, "wrap, dock center");
panel.add(yesButton);
panel.add(noButton);
return panel;
}
Then, I add it to gamePanel, then gamePanel to mainPanel, then mainPanel to the frame.
gamePanel.add(YesOrNoPanel, "align center");
mainPanel.add(gamePanel);
add(mainPanel);
I'm unsure of what would be causing yesOrNoText to not become fully centered within the YesNoPanel. Please let me know if I need to clarify anything!
Thank you.
I needed to make the add call for the yesNo label span 2 cells. By adding one component in the first row, then adding two in the next, I essentially created a 2x2 grid.
panel.add(yesOrNoText, "wrap, align center, span 2 1");
panel.add(yesButton);
panel.add(noButton);
Notice that on the first component I add yesOrNoText I use span to tell MiGFormat to take up two cells for this component. I can then center that with the remaining two components because it becomes the only component in the row.
First off thanks for everyone who contributes. It's such a lifesaver. That said, here's my first ever post.
I've created a dynamic array of JButton objects and attached an ActionListener to the button.
public void printFound(ArrayList<Customer> found)
{
buttons = new ArrayList();
texts = new ArrayList();
for(Customer temp: found)
{
JButton btn = new JButton("Edit");
btn.addActionListener(new PushEdit());
btn.setPreferredSize(new Dimension(100, 40));
panel1.add(btn);
buttons.add(btn);
JTextArea text = new JTextArea(temp.toString(), 8, 80);
text.setLineWrap(true);
panel1.add(text);
texts.add(text);
}
}
When I click on an edit button, I want it to pass the index of "btn" in "buttons" to the ActionListener so that I can display the values in "temp" in another GUI. I figure I either need to pass temp directly or I need to pass both the index of "btn" as well as the index of "found".
Thanks!
as i can understand from your question you want to get the index of the jbutton that stored in buttons ArrayList to do some sort of things..
to do this you can use setActionCommand and getActionCommand methods to bind a String along with every jbutton that created and
so your code will be like this
public void printFound(ArrayList<Customer> found)
{
buttons = new ArrayList();
texts = new ArrayList();
Integer index=0;
for(Customer temp: found)
{
JButton btn = new JButton("Edit");
btn.setActionCommand(index.toString());
btn.addActionListener(new PushEdit());
btn.setPreferredSize(new Dimension(100, 40));
panel1.add(btn);
buttons.add(btn);
JTextArea text = new JTextArea(temp.toString(), 8, 80);
text.setLineWrap(true);
panel1.add(text);
texts.add(text);
index=index+1;
}
}
whenever you you want to get the index
System.out.print(btn.getActionCommand());
I'm creating a list of bank movements with the following code. pane is a JPanel and array is an ArrayList that contains respectively amount and description data. Setting is a little icon that allow you to modify each movement.
MouseClass is a class that extends MouseAdapter that I've created to add "k" index to mouseClicked method. I'm new with java gui programming. I'd like to know if there is a quick method to add a scroll to my panel
JLabel[] movement = new JLabel[array.size()];
JLabel[] description = new JLabel[array.size()];
JLabel[] data = new JLabel[array.size()];
JLabel[] setting = new JLabel[array.size()];
System.out.println(array.size());
int i = 0;
for(int k=0; k<array.size(); k++){
movement[k] = new JLabel("");
movement[k].setForeground(SystemColor.text);
movement[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
movement[k].setBounds(17, i, 145, 30);
movement[k].setText(array.get(array.size() - k - 1).getAmount() + "€");
panel.add(movement[k]);
description[k] = new JLabel("");
description[k].setForeground(SystemColor.text);
description[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
description[k].setBounds(187, i, 274, 30);
description[k].setText(array.get(array.size() - k - 1).getDescription());
panel.add(description[k]);
data[k] = new JLabel("");
data[k].setForeground(SystemColor.text);
data[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
data[k].setBounds(478, i, 145, 30);
data[k].setText(array.get(array.size() - k - 1).getDate());
panel.add(data[k]);
setting[k] = new JLabel();
setting[k].setIcon(new ImageIcon(List.class.getResource("/it/andreavaiuso/financemanager/images/edit.png")));
setting[k].setForeground(SystemColor.text);
setting[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
setting[k].addMouseListener(new MouseClass(array.size() - k - 1) {
#Override
public void mouseClicked(MouseEvent arg0) {
Modify mdf = new Modify(this.index);
mdf.setVisible(true);
dispose();
}
});
setting[k].setBounds(640, i, 82, 30);
panel.add(setting[k]);
i += 40;
}
But I don't know how to scroll it. I've tried woth JScrollPane but don't work!
I'm sure there is a simplest way to add these items to my panel...
I've tried woth JScrollPane but don't work!
Well I see lots of code with setBounds(...) which implies you are using a null layout.
Don't use a null layout. Swing was designed to be used with layout managers. In fact the scroll pane will only work when used with a layout manager because the scroll pane needs to know the preferred size of the panel so it can determine when you use scrollbars.
I would also suggest you should also be using a JTable for something like this. It is more efficient because you don't need to create individual components for each row of data. Read the section from the Swing tutorial on How to Use Tables for more information and examples.
For a JScrollPane you need, 1 JScrollPane, 1 JList and one DefaultListModel.
First you add your items to DefaultListModel, then you add the model to the JList and then you make a JSCrollPane with passing as argument your JList
Example:
DefaultListModel model = new DefaultListModel<String>();
JList list = new JList<String>();
model.addElemenet("1");
model.addElemenet("3");
model.addElemenet("2");
list.setModel(model);
JScrollPane scrollPane = new JScrollPane(list);
Here is the code that I am trying to edit:
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
JLabel bbbl = new JLabel(bbb);
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbHl = new JLabel(bbbH);
game.setLayout(new GridLayout(2,2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1)
{
game.remove(bbol);
game.add(bboHl);
}
else
{
}
I want the JLabel bboHl to go in the same position as the JLabel bbol however there are other JLabels after this one, 3 more to be exact, therefor explaining why the layout is (GridLayout(2,2))
Would I need to change the layout?
Removing/adding components to the layout is way too expensive.
From what I understand, you just want to toogle an image :
Add only one JLabel, and use setIcon on it to change the image.
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbl = new JLabel(bbb);
game.setLayout(new GridLayout(2, 2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1) {
bbbl.setIcon(bbbH);
} else {
bbbl.setIcon(bbb);
}
Let say if there are multiple labels like label1 ,label2 , label3etc. And you want to set them on the position of label bbo1. Then it can be done by getting the location of label bbo1 and setting it to all other labels.
For Example
label1.setLocation(bbo1.getLocation());
label2.setLocation(bbo1.getLocation());
label3.setLocation(bbo1.getLocation());
I am trying to create a window that shows a dynamic list of textFields and
if the number of textfields is large then I want to add a scroller.
I am using GridLayout.
The problem is that the panel I added the Jlist and scroller doesn't show anything, neither the list nor the scroller. Below you will find a part of my code.
//Label
JLabel numberOfTxt = new JLabel("Please enter the number in every TextField");
int n = 11; //A random number of TextFields
firstPanel.add(numberOfTxt, BorderLayout.NORTH); //Add label to panel
JList textFieldList = new JList(); //Create a list of TextFields
for (int i = 0; i < n; i++) {
//Add TextFields to list
JTextField textField = new JTextField();
textField.setBounds(0, 0, 6, 0);
textFieldList.add(textField);
System.out.println("textFieldList" + textFieldList);
}
textFieldList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
textFieldList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
textFieldList.setVisibleRowCount(8);
//Create scroller
JScrollPane listScroller = new JScrollPane(textFieldList);
listScroller.setBounds(0, 20, 600, 600);
//Create layout for panel where the textfields will be added
if (n % 2 != 0) {
n = n + 1;
}
thirdPanel.setLayout(new GridLayout(n / 2, 2, 10, 6));
thirdPanel.add(textFieldList);
thirdPanel.setVisible(true);
//ContentPane has BoxLayout
contentPane.add(firstPanel);
contentPane.add(thirdPanel);
contentPane.repaint();
window.pack();
}
window.revalidate();
}
});
JList does not works this way. If you really need a JList of TextFields you should use ListCellRenderer (probably you don't, see p.3).
You adding textFieldList both to listScroller and thirdPanel. Probably, you should replace thirdPanel.add(textFieldList); by thirdPanel.add(listScroller);.
thirdPanel uses GridLayout, but only one control is ever added to it. You should either add TextField directly to thirdPanel (easier way), or let the JList manage them.