Adding JButtons in for loop - java

JAVA Swing Problem
I want to create a list of JButtons based on a list of strings, which represents the button text.
In my first step, I collect my data for the button texts from an external text file. This data is stored in the data variable.
List<String> data = ReadFile("texts.txt")
Now I want to create the list of JButtons, named buttons. There I set their text and their Bounds. The Bounds are relative to the index, so the buttons are placed below each other. Finally, I add the button to the frame and to the buttons list.
List<JButton> buttons = new ArrayList<>();
for (int index = 0; index < data.size(); index++) {
JButton button = new JButton();
button.setText(data.get(index));
button.setBounds(0, index*50, 100, 50);
add(button);
buttons.add(button);
But when I execute this, the last Button ends big, the first ones also disappear when I don't hover over them, but that's based on the fact, that the last button ist placed above:
Picture of the executed script
The last button has the size of the frame, doesn't matter, if I resize the frame:
Picture of the resized screen
I hope someone can help me or tell me where I can find help. Thanks.

the last Button ends big, the first ones also disappear when I don't hover over them,
That is because by default the content pane of the JFrame uses a BorderLayout. When you add a component to the BorderLayout the button is added to the CENTER. However, only a single component can be added to the CENTER, so only the size/location of the last component added is managed by the BorderLayout.
Don't attempt to set the size/location of your components manually. It is the job of a layout manager to do this. In your case you can use a couple of panels with different layout so align your button in a column on the left. Something like:
JPanel buttonPanel = new JPanel( new GridLayout(0, 1) );
for (int index = 0; index < data.size(); index++) {
JButton button = new JButton();
button.setText(data.get(index));
button.setBounds(0, index*50, 100, 50);
//add(button);
buttonPanel.add( button );
buttons.add(button);
}
add(buttonPanel, BorderLayout.LINE_START);
Try the above code and you will notice that the buttons are all the same size, but the size keeps changing as the height of the frame changes.
So to prevent this resizing we need to allow the button to be displayed at their preferred height by using an additional layout manager:
//add(buttonPanel, BorderLayout.LINE_START);
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(buttonPanel, BorderLayout.PAGE_START);
add(wrapper, BorderLayout.LINE_START);
Read the Swing tutorial on Layout Manager for more information and examples.

Related

Change size of JButtons

I have a very big problem. I need to do vertical menu in the center of window. What could be easier? What I did:
I create JFrame and set BorderLayout to it:
JFrame jfr = new JFrame("Frame");
Then I create 4 buttons:
JButton b1 = new JButton("b1");
JButton b2 = new JButton("b2");
JButton b3 = new JButton("b3");
JButton b4 = new JButton("b4");
I created panel and add all buttons to panel:
JPanel jpan = new JPanel();
jpan.setLayout(new BoxLayout(jpan, BoxLayout.Y_AXIS));
jpan.add(b1);
jpan.add(b2);
jpan.add(b3);
jpan.add(b4);
Aligned all buttons
b1.setAlignmentX(JComponent.CENTER_ALIGNMENT);
b2.setAlignmentX(JComponent.CENTER_ALIGNMENT);
b3.setAlignmentX(JComponent.CENTER_ALIGNMENT);
b4.setAlignmentX(JComponent.CENTER_ALIGNMENT);
And add panel to JFrame
jfr.add(jpan, BorderLayout.CENTER);
Please help me to understand this layouts!
Only say like this: "You should use this, when you use this layout"
And now main question: How can I change size of buttons?
There are a number of easy ways to change the size of buttons:
Give the buttons an icon of a different size.
Make the font of the buttons a different size.
Set more / less space between the button contents (the icon and text) and the border of the button.
Give the buttons more / less text.
Given the last is quite arbitrary, here is a demonstration of the first 3 techniques:

Grid layout not working?

I am trying to make a 2x2 grid layout that has a JLabel on the top left, and three buttons on the other three spaces. When I do this, I get the unexpected result of one big button (filling up the entire JDialog) that says "Do you want to push me". I don't know why this result shows up, please help, Thanks!
public void sinceyoupressedthecoolbutton() {
JDialog replacementwindow = new JDialog(); //Like a window
JButton best = new JButton("best");
JButton first = new JButton("FIRST");
JButton second = new JButton("Second");
replacementwindow.setLayout(new GridLayout(2,3,0,0)); //Row, column, distance horizontally, distance vertical
JPanel panel = new JPanel();
replacementwindow.add(panel); //adding the JPanel itself
replacementwindow.add(first);
replacementwindow.add(second);
replacementwindow.add(best);
replacementwindow.setSize(500, 500);
replacementwindow.setTitle("NEW WINDOW!");
replacementwindow.setVisible(true);
}
It's because you set the layout of your JButton, and not of your JDialog
Change
label.setLayout(new GridLayout(2,2,0,0));
to
YES.setLayout(new GridLayout(2,2,0,0));
Also, your variable called label is a JButton, you probably want to change that.
Don't add components to a button. You add components to a panel.
So the basic code should be:
JDialog dialog = new JDialog(...);
JPanel panel = new JPanel( new GridLayout(...) );
panel.add(label);
panel.add(button1);
...
dialog.add(panel);
Also, variable names should NOT start with an upper case character! "Yes" does not follow Java standards. The other variables do. Be consistent!

Why does the last item added to a panel occupy the whole panel?

I'm adding a quantity of JTextField to a panel, and all of them are added but, the last one added takes the whole panel and seems all other text boxes added on the last one..... here is the code
public JPanel crearCartonFormulario() {
panel = new JPanel();
panel.setLayout(new BorderLayout());
JTextField[] textBoxes = new JTextField[25];
int cont = 0;
int posX = 10;
int posY = 0;
llenarArreglo();
while (cont <= 4) {
for (int i = 0; i <= 4; i++) {
if (cont == 2 && i == 2) {
textBoxes[i] = new JTextField("");
} else {
textBoxes[i] = new JTextField(String.valueOf(numeros[cont][i]));
}
textBoxes[i].setBounds(i + posX, 15 + posY, 40, 40);
textBoxes[i].setEditable(false);
panel.add(textBoxes[i]);
posX += 50;
}
posY += 50;
posX = 10;
cont++;
}
return panel;
}
This is returned at a panel where I keep multiple panels of this one, it works but in this one the last JTextField takes the whole panel space....
The new JFrame that contains the panels created by the method, adopt the last JTextField size and that text box doesn't take the bounds indicated by the method, but all the other text boxes still inside and correctly added.
panel.setLayout(new BorderLayout());
You are using a BorderLayout.
panel.add(textBoxes[i]);
When you use the add() method the default is to add the component to the CENTER of the BorderLayout. However, only a single component can be added to the center so the layout manager will only manage the size/location of the last component added. The rules of the BorderLayout is to make the component take up all the available space.
However, you have also used the setBounds() methods for the other text fields which is causing a problem. You should NOT attempt to use a layout manager and manage the bounds of the components yourself.
The solution is to just use a layout manager and let the layout manager do its job. Read the section from the Swing tutorial on Using Layout Managers for more information and use a more appropriate layout manager.
Update:
its a bingo table
Then maybe you shouldn't even be using JTextFields. Maybe a JTable would be a better component to use. The tutorial also has a section on How to Use Tables.
Your problem is here:
panel.setLayout(new BorderLayout());
You set the layout to BorderLayout and yet add components to the JPanel as if it were a GridLayout. Understand that when you add components to a BorderLayout-using container in a default way, the components get added in the BorderLayout.CENTER position which fills this position, covering anything added prevsiously.
Perhaps you wish to use a GridLayout instead? You will want to read the layout manager tutorial for more.
This is because you are using BorderLayout and BorderLaout Always requires a parameter like BorderLayout.CENTER, BorderLayout.WEST, BorderLayout.EAST, BorderLayout.NORTH and BorderLayout.SOUTH.
So basically BorderLayout only has 5 position where a component can go. And if you do not specify where when adding a component it defaults to BorderLayout.CENTER. And as there can only be one component at a time in the BorderLayout.CENTER position it only really adds the last one. So I'd suggest an other layout manager like GridLayout( if you want all the components to be equally sized).
I hope this helps :).
P.S. If you want me to give some explination on GridLayout just ask.

How can i show the jpanel?

I make a movie theater system. And i keep the movies and movie theaters in a jTable. Also I'm trying to show the movie theater. Movie theater seats made from JButton and I keep these seats in a jpanel.
How can i show the seats when the movie theater selected?
And this is my code.
final ArrayList<JPanel> panels = new ArrayList<>();
for(int k=0;k<theater.size();k++){
JPanel panel = new JPanel();
panel.setBounds(500, 0, 500, 500);
contentPane.add(panel);
int y = theater.get(k).getCapacity();
int x = 500/y;
for(int i=0;i<y;i++){
for(int j=0;j<y;j++){
JButton button = new JButton(letters[i]+numbers[j]);
button.setBounds(500 + x*j, 0 + x*i, x-5, x-5);
panel.add(button);
}
}
repaint();
panels.add(panel);
}
Don't use setBounds() method instead leave it for Layout Manger to set the size and position of the components that why it's made for.
Use proper layout for this design such as GridLayout, GridBagLayout etc.
Read more about layout How to Use Various Layout Managers
Don't directly add the components in the JFrame's content pane instead first add the components in another container such as JPanel then finally add it in the JFrame's content pane.

Jlabel array not visible in netbeans while creating dynamically

I am not able to view the labels which are created dynamically.The code is as follows :
JLabel[] labels = new javax.swing.JLabel[cur.length];
for (int i = 0 ;i < cur.length; i++)
{
System.out.println("in");
labels[i] = new JLabel( cur[i] );
labels[i].setText(""+cur[i]);
jPanel1.add(labels[i]);
this.setVisible(true);
}
}
There can one or many of cause for your problem
1. Your JPanel may not be added to Container. Add it using getContentPane().add(jpanel1);
2. Your JLabel itself are not visible. Set their visible property to true.
3. Your JPanel is not having flowlayout but CardLayout and hence they might be visible in the back of other component. Assign the layout using jpanel1.setLayout(new FlowLayout())
4. Shift your this.setVisible(true) to outside loop.
What layout are you having for your jPanel object ? try changing its layout to say, FlowLayout. Give it layout in the beginning where you defined it and then use it in your loop.

Categories