Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 制作JList';s选定的索引消失_Java_Swing_Windowbuilder - Fatal编程技术网

Java 制作JList';s选定的索引消失

Java 制作JList';s选定的索引消失,java,swing,windowbuilder,Java,Swing,Windowbuilder,因此,我的程序中有一个JList,它从所选索引0开始。但是,在程序中,我想执行myJList.setSelectedIndex(-1)或类似操作,以便不选择任何内容?希望我是清楚的。谢谢JList提供了清除选择的方法。看见检查和API以发现可用于更改选择的方法 编辑:因为您指出它不工作,所以我创建了一个显示ClearElection按预期工作的对话框 public class Test { public static void main( String[] args ) { try

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

JList
提供了清除选择的方法。看见检查和API以发现可用于更改选择的方法

编辑:因为您指出它不工作,所以我创建了一个显示ClearElection按预期工作的对话框

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 ) {
    }
  }
}
那么:

SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            jList.clearSelection();
        }
}
另一种方式:

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

编辑:我的坏,它工作有另一个错误。由于某种原因,选举不起作用。当我调用该方法时(至少以可见的方式)不会发生任何事情。同一个列表元素仍然保持高亮显示。因此,我的问题是列表中有一个valueChanged事件,我认为clearSelection会触发它,从而导致空指针异常。是的,我错过了此方法,即使我逐一查看了方法列表:)谢谢。既然罗宾是第一个,我会给他打勾希望你不介意(不过我会给你一个放弃)