在我的程序中,用户必须首先选择房间数,然后选择每个房间的成人和儿童数。如果孩子人数超过0,则用户必须输入他们的年龄。作为布局,我使用GridBagLayout,但是我不了解如何将这些具有年龄的组合框与带有子级编号的组合框定位在同一行。在这种情况下有人可以建议我吗?
public class Selection extends JFrame {
JLabel rooms;
JComboBox r;
public Selection() {
final GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
final GridBagConstraints c = new GridBagConstraints();
rooms = new JLabel("Rooms:");
String[] x = {"1", "2", "3", "4", "5"};
r = new JComboBox(x);
r.setBackground(Color.WHITE);
r.addActionListener(new ActionListener() {
JComboBox[] adults;
JComboBox[] children;
public void actionPerformed(ActionEvent e) {
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.NONE;
c.gridheight = 1;
c.gridwidth = 1;
c.gridx = GridBagConstraints.VERTICAL;
c.insets = new Insets(10, 10, 0, 0);
c.gridx = GridBagConstraints.HORIZONTAL;
remove(r);
remove(rooms);
String[] str = {"1", "2", "3", "4", "5"};
String[] str1 = {"0", "1", "2", "3", "4", "5"};
final String[] str2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17"};
adults = new JComboBox[5];
children = new JComboBox[5];
final JComboBox[] ages = new JComboBox[5];
final JLabel[] adultLabels = new JLabel[5];
JLabel[] childrenLabels = new JLabel[5];
final JLabel[] ageLabels = new JLabel[5];
for (int i = 0; i < 5; i++) {
adultLabels[i] = new JLabel("Adults in room " + (i + 1) + ":");
childrenLabels[i] = new JLabel("Children in room " + (i + 1) + ":");
adults[i] = new JComboBox(str);
adults[i].setBackground(Color.WHITE);
children[i] = new JComboBox(str1);
children[i].setBackground(Color.WHITE);
final int finalI = i;
children[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int h = 0;
for (int j = 0; j < children[finalI].getSelectedIndex(); j++) {
h += 2;
ageLabels[j] = new JLabel("Age " + (j + 1) + ":");
ages[j] = new JComboBox(str2);
ages[j].setBackground(Color.WHITE);
c.gridx = 8;
c.gridy = h;
gbl.setConstraints(ageLabels[j], c);
add(ageLabels[j]);
//c.gridx = 7;
gbl.setConstraints(ages[j], c);
add(ages[j]);
}
getContentPane().validate();
}
});
}
for (int i = 0; i <= r.getSelectedIndex(); i++) {
c.gridx = GridBagConstraints.VERTICAL;
gbl.setConstraints(adultLabels[i], c);
add(adultLabels[i]);
gbl.setConstraints(adults[i], c);
add(adults[i]);
gbl.setConstraints(childrenLabels[i], c);
add(childrenLabels[i]);
gbl.setConstraints(children[i], c);
add(children[i]);
}
getContentPane().validate();
}
});
gbl.setConstraints(rooms, c);
add(rooms);
gbl.setConstraints(r, c);
add(r);
}
}
public class MainClass {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame selection = new Selection();
selection.setExtendedState(Frame.MAXIMIZED_BOTH);
selection.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
selection.setVisible(true);
selection.getContentPane().setBackground(Color.WHITE);
}
});
}
}