简体   繁体   中英

Java jTable data from ArrayList objects and update from other methods

I'm new to Java GUI and trying to work with jTable's in SWING. I currently have one which I made by following the Oracle tutorial and it gets the table data by using:

Object[][] data = {
    {"Kathy", "Smith",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"John", "Doe",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Sue", "Black",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Jane", "White",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Joe", "Brown",
     "Pool", new Integer(10), new Boolean(false)}
};

I have an object called Orders which has an ArrayList (productsInOrder) which contains an unlimited number of Project objects. I am trying to get the table to display each of the following for each object in the ArrayList. productsInOrder.getPrice() productsInOrder.getSKU() productsInOrder.getName()

Can anyone point me in the right direction? Or link me to a tutorial that can help as I've looked all over the internet and can not figure this out.

Finally, I have elsewhere I have an action listener which adds more Product objects to the ArrayList when the user performs certain actions. How would I update the jTable? Simply by reloading the whole jTable in the action listener or is there a way to simply add another row to the table?

Or link me to a tutorial that can help

The tutorial you've read is the tutorial that should help you.

The basic solution is to create a custom TableModel. In the example they store the data in a 2D array. In your case the data will be stored in an ArrayList. Therefore you will need to modify the getVAlueAt() method to access the ArrayList instead of the 2D array.

Finally, I have elsewhere I have an action listener which adds more Product objects to the ArrayList when the user performs certain actions.

Your code should update the TableModel, not the ArrayList. Then the table model will notify the table. This means you need to implement an addRow(...) method in your custom TableModel.

For a more complex solution you can create a generic table model which can be used. See the Bean Table Model for an example of this approach. The JButtonTableModel example code shows how you can further customize the BeanTableModel for only the properties you are interested in.

The Definitive Guide to Swing by John Zukowski is an excellent resource on Swing. It addresses everything very methodically with relevant examples. Highly recommend it.

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