根据JComboBox上的选定项目在GridBagLayout上添加组件

时间:2019-04-20 08:24:36

标签: java swing layout-manager gridbaglayout

我有一个GridBagLayout和其中的一些组件as shown in this figure

现在,我想在“值”列下的gridx=3; gridy=1上添加组件。这些成分根据JComboBox中选择的项目而有所不同(例如,当选择“性别”项时,将显示一个带有M,F的组合框),而当选择“年龄”项时将显示JTextField

现在的问题是,即使我设置了gridx=3; gridy=1,这些组件也不会显示在同一行中,而是显示在另一个位置as shown in this figure

我该如何解决?

代码如下所示:

public class FilterPanel extends JPanel {

private JLabel field = new JLabel("Field");
private JLabel operator = new JLabel("Operator");
private JLabel value = new JLabel("Value");
private String[] attrs = { "----------------", "Sex", "Age"};
private JComboBox<String> attrList = new JComboBox<String>(attrs);
private JComboBox<String> opListString = new JComboBox<String>();
private JTextField txt = new JTextField(9);
private GridBagConstraints gbc;

public FilterPanel() {

    Dimension size = getPreferredSize();
    size.width = 500;
    size.height = 300;
    setPreferredSize(size);
    setLayout(new GridBagLayout());
    gbc = new GridBagConstraints();
    setBorder(BorderFactory.createTitledBorder("Filter Condition"));

    // First row
    gbc.weightx = 0.5;

    gbc.gridx = 1;
    gbc.gridy = 0;
    this.add(this.field, gbc);

    gbc.gridx++;
    this.add(this.operator, gbc);

    gbc.gridx++;
    this.add(this.value, gbc);

    // Second row
    gbc.gridx = 0;
    gbc.gridy = 1;
    this.add(new JLabel("1"), gbc);

    gbc.gridx = 1;
    // SET DIMENSION
    attrList.setPrototypeDisplayValue("XXXXXXXXXXXXXX");
    this.add(attrList, gbc);

    gbc.gridx = 2;
    //SET DIMENSION
    opListString.setPrototypeDisplayValue("XXXXXXX");
    this.add(opListString, gbc);


    //gbc.gridx = 3;
    //this.add(txt, gbc);

    attrList.addActionListener((ActionEvent) -> {               
        String choose = attrList.getSelectedItem().toString();
        switch(choose) {
        case "----------------": {
            removeItem();
            break;
        }
        case "Age": {
            removeItem();
            addOpsString();
            addValueComp();
            break;
        }
}
    });

    gbc.gridx = 4;
    this.add(new JButton("Rem"), gbc);

    // Third row
    gbc.weighty = 10;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.gridx = 1;
    gbc.gridy = 2;
    this.add(new JLabel("Add"), gbc);

}

public void addOpsString() {
    opListString.addItem("is equals");
}

public void removeItem() {
    opListString.removeAllItems();
}

public void addValueComp() {
    gbc.gridx = 3;
    gbc.gridy = 1;
    this.add(txt,gbc);
}
}

0 个答案:

没有答案