gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:42:23 25 4
gpt4 key购买 nike

因此,我的 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>

关于java - 从组合框中选择时如何突出显示特定标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com