gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:42:05 26 4
gpt4 key购买 nike

这是整个类的摘录,基本上我在类中声明了一个 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);
}
});
}
});

最佳答案

您正在 `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);
}
});
}

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

关于Java JList.getSelectedIndex() 始终返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29443308/

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