因此,我的JComboBox中有一个用户数据库,左侧也是这些用户的列表。我想做的是从JComboBox中选择该用户时编写一个程序,在左侧的list(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<JLabel>更改为JList<String>

09-05 14:59