display a table of ArrayList

前端 未结 1 1765
礼貌的吻别
礼貌的吻别 2021-01-22 20:21

I have a main.java that has a button, when you press it, it calls a method and retuns an ArrayList of Nodes; I want to display the ArrayList in a table ( 5 fields a

相关标签:
1条回答
  • 2021-01-22 20:41

    As discussed in Creating a Table Model, let Nodes extend AbstractTableModel and implement the required methods. Use the resulting model to create your JTable.

    Addendum: Here's an outline of the model. The fields name and value can use the default renderer, but you'll have decide how to render the Lists found in each Node.

    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.table.AbstractTableModel;
    
    /** @see http://stackoverflow.com/questions/5438516 */
    public class Nodes extends AbstractTableModel {
    
        private List<Node> nodes = new ArrayList<Node>();
    
        @Override
        public int getRowCount() {
            return nodes.size();
        }
    
        @Override
        public int getColumnCount() {
            return 5; // A Node has five members
        }
    
        @Override
        public Object getValueAt(int row, int col) {
            Node node = nodes.get(row);
            switch (col) {
                case 0:
                    return node.name;
                case 1:
                    return node.value;
                case 2:
                    return node.first;
                case 3:
                    return node.second;
                case 4:
                    return node.values;
                default:
                    return null;
            }
        }
    
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    
        private class Node {
    
            private String name;
            private double value;
            private List<Node> first;
            private List<Node> second;
            private List<Double> values;
        }
    }
    
    0 讨论(0)
提交回复
热议问题