因此,我的程序中有一个 JList,它从选定的索引 0 开始。但是,在程序中我想做 myJList.setSelectedIndex(-1) 或类似的事情,以便什么都没有选择?希望我很清楚。谢谢
问问题
2768 次
2 回答
4
JList
有一种清除选择的方法。见JList#clearSelection
。检查API 以发现可用于更改选择的JList#getSelectionModel
方法ListSelectionModel
编辑:由于您表示它不起作用,我创建了一个SSCCE,显示 clearSelection 按预期工作
public class Test {
public static void main( String[] args ) {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().setLayout( new BorderLayout( ) );
DefaultListModel listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
final JList list = new JList( listModel );
list.setSelectedIndex( 0 );
frame.getContentPane().add( list, BorderLayout.CENTER );
JButton clearSelectionButton = new JButton( "Clear selection" );
frame.getContentPane().add( clearSelectionButton, BorderLayout.SOUTH );
clearSelectionButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent aActionEvent ) {
list.clearSelection();
}
} );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
} );
} catch ( InterruptedException e ) {
} catch ( InvocationTargetException e ) {
}
}
}
于 2011-12-30T19:10:47.197 回答
3
怎么样:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jList.clearSelection();
}
}
另一种方式:
jButton1.addActionListener(
(ActionListener)EventHandler.create(ActionListener.class, jList1, "clearSelection"));
于 2011-12-30T19:18:04.733 回答