Highlight selected JList index

So, I have a JList in my program, and it starts with the selected index 0. However, during the program I want to execute myJList.setSelectedIndex (-1) or something similar so that nothing is selected? I hope I get it. Thanks

+4
source share
2 answers

JList has a way to clear selection. See JList#clearSelection . Check the JList#getSelectionModel and ListSelectionModel API to find out which methods are available for selection

Edit: since you indicated that this does not work, I created SSCCE , showing that clearSelection works as expected

 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 ) { } } } 
+4
source

What about:

 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { jList.clearSelection(); } } 

Another way:

  jButton1.addActionListener( (ActionListener)EventHandler.create(ActionListener.class, jList1, "clearSelection")); 
+3
source

Source: https://habr.com/ru/post/1388647/


All Articles