Jlabel array not visible in netbeans while creating dynamically - java

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.

Related

Adding JButtons in for loop

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.

Is it possible to place components randomly without container in Swing window builder?

The only way, as far as I know, to put a JButton or a JLabel is via creating the GUI structure through Containers and placing those components on it.
Are there other methods to add components randomly into the frame and resize accordingly ,as can be done in Visual C# for example? What is the method to do it?
Yes.
You could use a null Layout and then place components using setBounds().
For example:
JPanel panel = new JPanel(null);
for (int i = 0; i < 4; i++) {
JButton b = new JButton("JButton-"+i);
b.setBounds(50+i*10, 50+i*10, 100, 100);
panel.add(b);
}
If you want random placing, you could random the first 2 (x,y) values.
You will need to provide on your own valid values to be placed inside the parent container.

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.

mixing gridlayout and borderlayout

I was tired but before quitting just stuck in the nearly-last 3 lines in the code snippet below to make a "refresh" button on my tictactoe panel, hoping to get away with it but expecting errors, since it mixes layout managers on a single container.
But it WORKED.
ButtonPanel.setLayout(new GridLayout(3, 3));
guiFrame.add(ButtonPanel);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
button[i][j] = addButton(ButtonPanel, i, j);
}
}
JButton refreshbutton = new JButton("Refresh");
guiFrame.add(refreshbutton, BorderLayout.SOUTH); // ... border layout worked. Hm.
refreshbutton.addActionListener(this);
guiFrame.setVisible(true); }
Should I be surprised? (Keep in mind my newbieness.)
(BOY, did I learn/stumble onto a buncha stuff in writing this silly game's program!!!--for instance, using setActionCommand to "label" each button internally [as 11,12,13,21,...33] so the ONE actionPerformed method could use getActionCommand to correctly label [with X or O] whatever button was pushed by whoever's turn it was.)
guiFrame.add(refreshbutton, BorderLayout.SOUTH); // ... border layout worked. Hm.
Just because you used BorderLayout.SOUTH does not make a panel a BorderLayout. Your code worked because the default layout manager for the content pane of a JFrame (JDialog) is a BorderLayout. So you are just taking advantage of the default layout.
since it mixes layout managers on a single container.
Yes, this is a common practice. In fact it is almost impossible to create a reasonably complex GUI if you don't use different layout managers on different panels that you add to a GUI.

Placing JTextFields in a JFrame of a Java GUI

I have:
public class BaseStationFrame1 extends JFrame
{
JButton activateButton;
JButton deactivateButton;
BaseStation bs;
JTextField networkIdField;
JTextField portField;
public BaseStationFrame1(BaseStation _bs){
bs = _bs;
setTitle("Base Station");
setSize(600,500);
setLocation(100,200);
setVisible(true);
activateButton = new JButton("Activate");
deactivateButton = new JButton("Deactivate");
Container content = this.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(activateButton);
content.add(deactivateButton);
networkIdField = new JTextField("networkId : "+ bs.getNetworkId());
networkIdField.setEditable(false);
content.add(networkIdField);
portField = new JTextField("portId : "+ bs.getPort());
portField.setEditable(false);
content.add(portField);}
}
My problem is that i don't want the two TextFields to appear on the right of Activate and Deactivate buttons but below them. How can i fix that?
Specify your layout manager, like this:
content.setLayout(new GridLayout(2,2));
That would use the Grid Layout Manager to establish a grid with 2 columns and 2 rows, that your components would then be placed in.
The layout manager you are currently using, FlowLayout, only adds contents onto the end of the current row. it will wrap around once it reaches the constrained edge of the pane, though.
You should also check the other layout managers here
You could alternatively use GridBagLayout , but you will have to specify a GridBagConstraints object you then add alongside the individual elements, like so:
content.add(networkIdField, gridConstraints);
see more on that in the linked tutorial.
can I suggest that you use a Null Layout for the parent component?
setLayout(null);
then use a setBounds(xPos,yPos, Width, Height);
to position the components on the panel etc?
Doing this will prevent Java's UI Manager to manage the components to the Frame, Panel etc.
That seems to be the easiest and less painful way.
Regards

Categories