Java JList.getSelectedIndex()始终返回-1

时间:2015-04-04 06:01:43

标签: java swing actionlistener jlist

这是整个类的摘录,基本上我已经在类中声明了一个JList和一个DefaultListModel,并创建了一个包含一些按钮和一个列表框的JFrame。单击roomsButton时,hotel.displayRoomsAvailable()函数将使用一些选项填充列表框,并将leftButton设置为可见和已分配的功能。正在使用函数的返回正确填充此列表框,但是,当我单击leftButton时,list.getSelectedIndex()始终返回-1,我尝试使用getSelectedValue(),但它返回null。我没做错,没有认识到列表中选择的正确值。列表中只有2个值,因此我认为它与ScrollPane无关或可见,等等

private JList<String> list;
private static DefaultListModel listModel;

listModel = new DefaultListModel();

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel cusPanel = new JPanel();
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setPreferredSize(new Dimension(400, 200));
cusPanel.add(list);
frame.add(cusPanel, BorderLayout.CENTER);

JButton roomsButton = new JButton("Display Rooms");
roomsButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent event)
    {
        listModel.clear();
        String startd = start.getText();
        String endd = end.getText();
        LocalDate startdate = LocalDate.parse(startd, DateTimeFormat.forPattern("MM/dd/yyyy"));
        LocalDate enddate = LocalDate.parse(endd, DateTimeFormat.forPattern("MM/dd/yyyy"));
        hotel.displayRoomsAvailable(startdate,enddate);
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setPreferredSize(new Dimension(400, 200));
        leftButton.setText("Reserve Room");
        leftButton.setVisible(true);
        leftButton.addActionListener(new ActionListener()
        {
           public void actionPerformed(ActionEvent event)
           {                
               System.out.println(list.getSelectedIndex());
               //hotel.bookRoom(true, ID, list.getSelectedValue(), startdate, enddate);
           }
        });
    }
});

1 个答案:

答案 0 :(得分:1)

您在`actionPerformed方法中创建了JList的新实例,但从未将其添加到屏幕上,因此永远无法选择它...

 public void actionPerformed(ActionEvent event)
    {
        //...
        list = new JList(listModel);
        //...
        leftButton.addActionListener(new ActionListener()
        {
           public void actionPerformed(ActionEvent event)
           {                
               System.out.println(list.getSelectedIndex());
               //hotel.bookRoom(true, ID, list.getSelectedValue(), startdate, enddate);
           }
        });
    }

坦率地说,我不明白你为什么会......