Reputation: 163
I have problem with multiple CheckBoxes. When I create them with my code it only show last box "bolonska zmes" and other boxes are shown only when mouseover. I think that it might be some problem with layers, but I dont know what to do. Thank you for help.
public class OknoPizzaVlastna extends JFrame
{
private String nazvy[] = { "cesnak", "feferony", "hrasok", "cibula",
"kecup", "tatarskaOmacka", "vajce",
"kapia", "fazula", "kukurica", "ananas", "brokolica",
"Niva", "Mozarella", "olivy", "inovec udeny", "articoky",
"klobasa", "sampiony", "salama", "slanina", "hranolky", "tuniak",
"sunka", "kuracie maso", "syr", "Morska zmes", "bolonska zmes"};
private JCheckBox boxes[];
public OknoPizzaVlastna()
{
boxes = new JCheckBox[nazvy.length];
for (int i = 0; i < nazvy.length; i++)
{
createrCheckBox(i);
}
setTitle("Vlastna Pizza");
setSize(480,320);
setVisible(true);
setResizable(true);
getContentPane().setLayout(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void createrCheckBox(int i)
{
boxes[i] = new JCheckBox();
//proper locations will be solved later
boxes[i].setLocation(62+i*30,54+i*20);
boxes[i].setSize(100,50);
boxes[i].setText(nazvy[i]);
boxes[i].setSelected(false);
boxes[i].setVisible(true);
getContentPane().add(boxes[i]);
}
}
Upvotes: 1
Views: 5928
Reputation: 168845
If the question were, 'how to layout this GUI?' the answer might be:
To organize the components for a robust GUI, use layout managers, or combinations of them, along with layout padding & borders for white space.
In this case, we use a single column GridLayout
, with an EmptyBorder
on each check box to successively indent them a larger amount as we proceed down the menu.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class OknoPizzaVlastna extends JFrame {
private String nazvy[] = {
"cesnak", "feferony", "hrasok", "cibula",
"kecup", "tatarskaOmacka", "vajce",
"kapia", "fazula", "kukurica", "ananas", "brokolica",
"Niva", "Mozarella", "olivy", "inovec udeny", "articoky",
"klobasa", "sampiony", "salama", "slanina", "hranolky", "tuniak",
"sunka", "kuracie maso", "syr", "Morska zmes", "bolonska zmes"
};
JPanel ui= new JPanel(new GridLayout(0,1,4,4));
private JCheckBox boxes[];
public OknoPizzaVlastna() {
ui.setBorder(new EmptyBorder(10,10,10,10));
setContentPane(ui);
boxes = new JCheckBox[nazvy.length];
for (int i = 0; i < nazvy.length; i++) {
createrCheckBox(i);
}
setTitle("Vlastna Pizza");
pack();
setVisible(true);
setResizable(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void createrCheckBox(int i) {
boxes[i] = new JCheckBox(nazvy[i]);
boxes[i].setBorder(new EmptyBorder(0,i*30,0,0));
ui.add(boxes[i]);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame frame = new OknoPizzaVlastna();
}
};
SwingUtilities.invokeLater(r);
}
}
Upvotes: 2