我有以下代码来创建JList:
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final JList list = new JList(nameData);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(5);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listScroller);
当未选择列表中的项目时,我有listSelectionListener()
的代码禁用按钮:
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
//No selection.
deleteConfirmButton.setEnabled(false);
} else {
//Selection.
deleteConfirmButton.setEnabled(true);
index = list.getSelectedIndex();
}
}
}
});
但是,是否选择了列表中的项目,按钮的状态不会改变。我该怎么办?
答案 0 :(得分:2)
您的deleteConfirmButton
disable-enable
逻辑不正确。首先,您需要disable
。在选择列表时,您应enable
,然后点击deleteConfirmButton
按钮再次显示disable
。阅读以下代码的评论。
final JButton deleteConfirmButton = new JButton("Kustuta");
deleteConfirmButton.setEnabled(false); //Disable here
deleteConfirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteConfirmButton.setEnabled(false);//Disable here
}
});
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
deleteConfirmButton.setEnabled(true);//Enable here
}
});
答案 1 :(得分:0)
假设deleteConfirmButton
位于名为rightPanel的JPanel
内,请调用repaint
和revalidate
方法再次绘制按钮。
if (list.getSelectedIndex() == -1) {
//No selection.
deleteConfirmButton.setEnabled(false);
} else {
//Selection.
deleteConfirmButton.setEnabled(true);
index = list.getSelectedIndex();
}
rightPanel.repaint();
rightPanel.revalidate();