从组合框中选择时,如何突出显示特定标签?

时间:2017-07-04 09:21:33

标签: java swing

所以我的JComboBox中有一个用户数据库,左侧是这些用户的列表。我想要做的是从JComboBox中选择此用户后编写程序,在左侧的list(JLabel)中突出显示该程序。我希望我足够具体。

1 个答案:

答案 0 :(得分:1)

public class Test2 extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel panel;
    private JComboBox<String> comboBox;
    private JList<String> list;

    public Test2() {
        panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);
        GridBagLayout gbl_panel = new GridBagLayout();
        panel.setLayout(gbl_panel);

        comboBox = new JComboBox<String>();
        comboBox.addItem("User1");
        comboBox.addItem("User2");
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.weightx = 1.0;
        gbc_comboBox.insets = new Insets(0, 0, 5, 0);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 0;
        gbc_comboBox.gridy = 0;
        panel.add(comboBox, gbc_comboBox);

        DefaultListModel<String> listModel = new DefaultListModel<>();
        listModel.addElement("User1");
        listModel.addElement("User2");

        list = new JList<String>(listModel);

        GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
        gbc_lblNewLabel.weightx = 1.0;
        gbc_lblNewLabel.gridx = 1;
        gbc_lblNewLabel.gridy = 0;

        panel.add(list, gbc_lblNewLabel);

        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String selectedItem = String.valueOf(comboBox.getSelectedItem());

                if (selectedItem.equals("User1"))
                    list.setSelectedValue("User1", true);
                else if (selectedItem.equals("User2"))
                    list.setSelectedValue("User2", true);
            }
        });
    }

    public static void main(String[] args) {
        Test2 myFrame = new Test2();
        myFrame.setVisible(true);
        myFrame.setSize(new Dimension(400, 500));
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

这对你有用吗?我不知道你为什么在JList中使用JLabel。所以我已将列表从JList<JLabel>更改为JList<String>