我遇到问题让JList与ListSelectionListener一起正常工作,我已尝试过匿名内部类并添加到我的Handler类并实现它,但两者都没有工作......
发生的事情是我有一个带有JComboBox的JFrame窗口,当你点击“颜色列表”时,弹出一个新的JFrame窗口,里面有一个JList,选项应该改变背景颜色......一切都是单击选项时,除了背景颜色没有变化,这是好的。我只会发布相应的代码......
private static String[] colorNames = {"Black", "Blue", "Red", "White"};
private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE};
public void colorListOption() {
TheHandler handler = new TheHandler();
newFrame2 = new JFrame();
panel3 = new JPanel();
newFrame2.setTitle("Welcome to The Color List!");
newFrame2.setLayout(new FlowLayout());
newFrame2.setSize(500, 300);
newFrame2.setDefaultCloseOperation(newFrame2.EXIT_ON_CLOSE);
colorList = new JList(colorNames);
colorList.setVisibleRowCount(4);
colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
colorList.setOpaque(false);
panel3.add(new JScrollPane(colorList));
newFrame2.add(panel3);
colorList.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ls) {
panel3.setBackground(colors[colorList.getSelectedIndex()]);
}
}
);
newFrame2.setVisible(true);
}