Listing objects in ArrayList in GUI and alternating between many ArrayLists

让人想犯罪 __ 提交于 2021-02-11 16:46:47

问题


I'm currently working on a personal project, in this project, the user is asked to create objects under 3 different categories, so after the object is created, there's a method that check's the category of the object and then it adds it to an ArrayList. More Details: the object is called Vehicle, there're three categories: Two wheels, three weels, three wheels. So, when you create a new Vehicle, you'd be asked to specify what kind of vehicles you're creating, say you said two wheels, a method will be called which will add the object into ArrayList twoWheelList, and so on.

I have two problems at the moment, I'm making a GUI for this program, where I'd like to display information stored in the ArrayLists, basically the user has a comboBox, which has the name of the three categories underneath it. I'd like that when the user chooses let's say "Two Wheels", a jList will list each object in the ArrayList twoWheelList

How can I make that happen? I've tried several times but I'm coming out with no luck. I'm using NetBeans, I don't really understand the whole JFrame concept and how to write the source codes, for the first problem where I'd need the program to know what did the user choose, should I just use an IF statement? How can I make the ArrayList of objects to be displayed in the jList?


回答1:


Start by adding an ItemListener to the JComboBox. In the itemStateChanged event, you will want to monitor the ItemEvent or the SELECTED state.

Get the selected value from the JComboBox. This may require you to provide some kind of look that can associate the item in the combo box with the ArrayList or, as I would prefer, a wrapper class which contained the name of the item an the ArrayList wrapped into a single object, which would provide the means to obtain the ArrayList

Then using a custom ListModel, you can wrap the ArrayList within it and apply it to the JList you have on the screen...

public class ProxyListModel extends AbstractListModel<Vehicle> {

    private List<Vehicle> vehicles;

    public ProxyListModel(List<Vehicle> vehicles) {
        // It might be better to simply make a copy of the list
        // but that's up to you...
        this.vehicles = vehicles;
    }

    @Override
    public int getSize() {
        return vehicles.size();
    }

    @Override
    public Vehicle getElementAt(int index) {
        return vehicles.get(index);
    }

}

Check out How to Use Combo Boxes and How to Use Lists for more details. Play close attention to the discussions about custom rendering.



来源:https://stackoverflow.com/questions/23281531/listing-objects-in-arraylist-in-gui-and-alternating-between-many-arraylists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!