简体   繁体   English

按下按钮更新JList

[英]Updating JList by pressing button

first of all I will introduce what I am trying to do. 首先,我将介绍我想做的事情。 This is an assignment in university we are making Hotel booking system with JAVA. 这是大学的一项工作,我们正在使用JAVA制作酒店预订系统。 To go straight to the point, all I need to know is how to update JList when I press button. 为了直截了当,我只需要按下按钮就可以更新JList。

    listModel = new DefaultListModel<Hotel>();
      bookingList = new JList(listModel);
class MouseAdapterMod extends MouseAdapter {

    public void mousePressed(MouseEvent e) {
  if(e.getSource() == searchButton){
     for(lists.getRoomsList() p : lists.getRoomsList())
     {
        listModel.addElement(p);
     }
     bookingList.setModel(listModel);
  }

In this GUI class I have instance variable (lists) of Hotel class, in Hotel class there are methods 在这个GUI类中,我有Hotel类的实例变量(列表),在Hotel类中有方法

    public ArrayList<Rooms> getRoomsList()
   {
      return roomsList.getListRooms();
   }
   public ArrayList<Suite> getSuitesList()
   {
      return roomsList.getListSuites();
   }

this returns whole ArrayList of Room class objects and also ArrayList of Suite class. 这将返回Room类对象的整个ArrayList以及Suite类的ArrayList。 QUESTION would be is how to show whole ArrayList of Rooms when I press button, in other words how to update JList which consists of objects, by pressing button? 问题是当我按下按钮时如何显示整个房间的ArrayList,换句话说如何通过按下按钮来更新由对象组成的JList? I hope I explained alright. 我希望我能解释清楚。

Your for-each loop is wrong. 您的for-each循环是错误的。 Try this and see: 试试看,看看:

public void mousePressed(MouseEvent e) {
  if(e.getSource().equals(searchButton)){
     ArrayList<Rooms> rooms = lists.getRoomsList();
     for(Rooms r : rooms) {
        listModel.addElement(r);
     }
     bookingList.setModel(listModel);
  }
}

This still looks sorta messy to me though. 不过,这对我来说仍然有些混乱。 A more appropriate approach would be to set an event handler on the searchButton , to populate the JList when searchButton is clicked. 一种更合适的方法是在searchButton上设置事件处理程序,以在单击searchButton时填充JList

Also, are Rooms and Suites sub classes of Hotel ? 此外,有RoomsSuites子类Hotel If not, you'll have to create listModel like this (for rooms): 如果没有,则必须创建这样的listModel (用于房间):

listModel = new DefaultListModel<Rooms>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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