gpt4 book ai didi

java - 使 JList 的选定索引消失

转载 作者:搜寻专家 更新时间:2023-11-01 01:56:06 26 4
gpt4 key购买 nike

所以我的程序中有一个 JList,它以选定的索引 0 开头。但是,在程序期间我想执行 myJList.setSelectedIndex(-1) 或类似的操作,以便不选择任何内容?希望我很清楚。谢谢

最佳答案

JList 有一个清除选择的方法。参见 JList#clearSelection .检查JList#getSelectionModelListSelectionModel用于发现可用于更改选择的方法的 API

编辑:既然你指出它不起作用,我创建了一个 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 ) {
}
}
}

关于java - 使 JList 的选定索引消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com