Reputation: 55
So I have a database of users in my JComboBox
and on the left side is a list of these users as well. What I want to do is write a program when this user is selected from the JComboBox
, highlight him in the list(JLabel)
on the left side. I hope I was specific enough.
Upvotes: 1
Views: 71
Reputation: 882
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);
}
}
Will this work for you?. I don't know why you are using JLabel inside JList. So i have changed the list from JList<JLabel>
to JList<String>
Upvotes: 1