在Java中未选择列表项时禁用按钮

时间:2013-11-18 12:43:13

标签: java swing

我有以下代码来创建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();
            }
        }
    }
});

但是,是否选择了列表中的项目,按钮的状态不会改变。我该怎么办?

2 个答案:

答案 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内,请调用repaintrevalidate方法再次绘制按钮。

if (list.getSelectedIndex() == -1) {
            //No selection.
      deleteConfirmButton.setEnabled(false);
} else {
      //Selection.
      deleteConfirmButton.setEnabled(true);
      index = list.getSelectedIndex();
}
rightPanel.repaint();
rightPanel.revalidate();