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

Java 从组合框中选择时,如何突出显示特定标签?,java,swing,Java,Swing,因此,我在JComboBox中有一个用户数据库,左侧是这些用户的列表。我想做的是编写一个程序,当这个用户从JComboBox中被选中时,在左侧的列表jLabel中突出显示他。我希望我说得够具体 public class Test2 extends JFrame { private static final long serialVersionUID = 1L; private JPanel panel; private JComboBox<String> c

因此,我在JComboBox中有一个用户数据库,左侧是这些用户的列表。我想做的是编写一个程序,当这个用户从JComboBox中被选中时,在左侧的列表jLabel中突出显示他。我希望我说得够具体

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更改为JList