简体   繁体   中英

How do I start a Jlist with the first item is selected?

I want to know how to start a JList with the first item selected when I click a button.

Here is what I have:

if(e.getSource() ==bButton)
{
  lQty.setSelectedIndex(0);
}

Sure it works. eg,

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class JListFun {
   public static void main(String[] args) {
      final JList<String> list = new JList<String>(new String[]{"one", "two", "three", "four", "five"});
      JScrollPane scrollPane = new JScrollPane(list);
      JButton btn = new JButton(new AbstractAction() {
         {
            putValue(NAME, "Press Me");
         }

         @Override
         public void actionPerformed(ActionEvent evt) {
            list.setSelectedIndex(0);
         }
      });
      JPanel panel = new JPanel();
      panel.add(scrollPane);
      panel.add(btn);
      JOptionPane.showMessageDialog(null, panel);
   }
}

If it doesn't work for you, you need to show us with compilable runnable code as shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM