java 将对象列表连接到 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7378013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:43:00  来源:igfitidea点击:

Connect a list of objects to a JTable

javaswinglist

提问by Ioannis Soultatos

I have a list of objects of type SI (SingleInstruction) in Java. Here is the SI class with its constructor.

我在 Java 中有一个 SI(SingleInstruction)类型的对象列表。这是带有构造函数的 SI 类。

    public class SI {
        private String recipe;
        private Integer makingOrder;
        private String instruction;
        private double estimatedTimeInMinutesSeconds;
        private Double timerInMinutesSeconds;
        private String timerEndingText;
        private boolean containsOtherInstructions = false;
        private List<SI> embeddedInstructionsList;

        public SI (String s1, Integer i1, String s2, double d1, Double d2, String s3){
            recipe = s1;
            makingOrder = i1;
            instruction = s2;
            estimatedTimeInMinutesSeconds = d1;
            timerInMinutesSeconds = d2;
            timerEndingText = s3;
        }
setters and getters methods ommited....

I need to have a table in my GUI that displays the data of this list. When I begin the program I create a

我的 GUI 中需要有一个表格来显示此列表的数据。当我开始程序时,我创建了一个

public List<SI> finalList = new ArrayList();

which is empty so I need an empty table to be displayed. The table should have columns of

这是空的,所以我需要一个空表来显示。该表应该有列

(String Recipe, Integer Order, String Instruction, double Est.time, Double Timer, String TimerText, boolean containOtherInstructions)

(String Recipe, Integer Order, String Instruction, double Est.time, Double Timer, String TimerText, boolean containsOtherInstructions)

Afterwards the finalList is filled with data and I need these data to be displayed in the table. In order to give you an example, I created a button that creates some SI and adds them to the finalList.

之后 finalList 填充了数据,我需要将这些数据显示在表格中。为了给你一个例子,我创建了一个按钮来创建一些 SI 并将它们添加到 finalList。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    SI si1 = new SI("Greek Salad", 1, "cut veggies", 4, null, null);
    SI si2 = new SI("Greek Salad", 2, "put spices", 1, null, null);
    SI si3 = new SI("Greek Salad", 3, "feta and finish", 1, null, null);
    SI si4 = new SI("Break", null, "Your free 10 minutes", 10, null, null);
    SI si5 = new SI("Meat", 1, "preheat oven", 0.5, 10.0, "oven is ready");
    SI si6 = new SI("Meat", 2, "spices on meat", 2, null, null);
    SI si7 = new SI("Meat", 3, "cook meat", 1, 10.0, "meat is ready");
    SI si8 = new SI("Meat", 4, "serve", 1, null, null);
    SI si9 = new SI("Break", null, "Your free 10 minutes", 10, null, null);
    SI si10 = new SI("Jelly", 1, "Boil water", 0.5, 4.0, "water is ready");
    SI si11 = new SI("Jelly", 2, "add mix and stir", 4, null, null);
    SI si12 = new SI("Jelly", 3, "share in bowls, wait 3 hours", 2, null, null);
    finalList.add(si1);
    finalList.add(si2);
    finalList.add(si3);
    finalList.add(si4);
    finalList.add(si5);
    finalList.add(si6);
    finalList.add(si7);
    finalList.add(si8);
    finalList.add(si9);
    finalList.add(si10);
    finalList.add(si11);
    finalList.add(si12);
}

Now I need that when I press the button, the table is updated and displays the data. I've tried a lot to find out how to do it but it is too hard. I'm not sure if I should extend AbstractTableModel or just use the defaultTableModel.

现在我需要当我按下按钮时,表格会更新并显示数据。我已经尝试了很多来找出如何去做,但这太难了。我不确定是否应该扩展 AbstractTableModel 或只使用 defaultTableModel。

To help you give me suggestions, the data of this table is final and user can't modify any cell. what should be allowed to the user to do though is to move rows up or down to change the order in the finalList.

为了帮助你给我建议,这个表的数据是最终的,用户不能修改任何单元格。但是应该允许用户做的是向上或向下移动行以更改 finalList 中的顺序。

PS: I am using netbeans, if you have any quick suggestions on the GUI builder.

PS:如果您对 GUI 构建器有任何快速建议,我正在使用 netbeans。

回答by Costis Aivalis

In Model-View-Controller Architecture the model is always responsible for the provision of data. If you use a model for your JTable the model provides the data.

在模型-视图-控制器架构中,模型始终负责提供数据。如果您为 JTable 使用模型,该模型将提供数据。

In order to create a model make a separate class that extends AbstractTableModel and has a constructor that creates all the SI objects you need and stores them to an ArrayList.

为了创建模型,请创建一个扩展 AbstractTableModel 的单独类,并具有一个构造函数,用于创建您需要的所有 SI 对象并将它们存储到 ArrayList。

 public class FinalTableModel extends AbstractTableModel {

    private List<SI> li = new ArrayList();
    private String[] columnNames = { "Recipe", "Order", "Instruction",
                "Est.time", "Timer", "Timer Label", "Has Subinstructions"};

    public FinalTableModel(List<SI> list){
         this.li = list;
    }

    @Override
    public String getColumnName(int columnIndex){
         return columnNames[columnIndex];
    }

    @Override     
    public int getRowCount() {
        return li.size();
    }

    @Override        
    public int getColumnCount() {
        return 7; 
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        SI si = list.get(rowIndex);
        switch (columnIndex) {
            case 0: 
                return si.getRecipe();
            case 1:
                return si.getMakingOrder();
            case 2:
                return si.getInstruction();
            case 3:
                return si.getEstimatedTimeInMinutesSeconds();
            case 4:
                return si.getTimerInMinutesSeconds();
            case 5:
                return si.getTimerEndingText();
            case 6:
                return si.isContainsOtherInstructions(); 
           }
           return null;
   }

   @Override
   public Class<?> getColumnClass(int columnIndex){
          switch (columnIndex){
             case 0:
               return String.class;
             case 1:
               return Integer.class;
             case 2:
               return String.class;
             case 3:
               return Double.class;
             case 4:
               return Double.class;
             case 5:
               return String.class;
             case 6:
               return Boolean.class;
             }
             return null;
      }
 }

Then make your JFrame and and create your JTable like this:

然后制作你的 JFrame 并像这样创建你的 JTable:

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    jTable1.setModel(new FinalTableModel(finalList));
    jScrollPane1.setViewportView(jTable1);

The idea is that JTable will autamatically request the data from the model, through call to getValueAt(row, col).

这个想法是 JTable 将通过调用 getValueAt(row, col) 自动从模型请求数据。

Netbeans makes it very easy to assign the model to your JTable. The model is a property of the JTable. Click the '...' button and choose "Custom code". Underneath create a model instance.

Netbeans 使将模型分配给 JTable 变得非常容易。模型是 JTable 的一个属性。单击“...”按钮并选择“自定义代码”。在下面创建一个模型实例。

enter image description here

在此处输入图片说明

回答by Hovercraft Full Of Eels

It's easier to use DefaultTableModel, but then you'll need to not use an ArrayList, but rather the data model held by the DefaultTableModel, though you could use your ArrayList to load the model.

使用 DefaultTableModel 更容易,但是您不需要使用 ArrayList,而是需要使用 DefaultTableModel 持有的数据模型,尽管您可以使用 ArrayList 加载模型。

You could construct the DefaultTableModel with an array of your column titles and 0 rows, and then add rows in a for loop, using your ArrayList above to create a Vector<Object>or an Object[], and then feed that into the model with its addRowmethod. Note that you could not add SI objects as a row, but instead would have to extract the data from each SI object and put it into the Object array or Object Vector.

您可以使用包含列标题和 0 行的数组构造 DefaultTableModel,然后在 for 循环中添加行,使用上面的 ArrayList 创建 aVector<Object>或 an Object[],然后使用其addRow方法将其输入模型。请注意,您不能将 SI 对象添加为一行,而是必须从每个 SI 对象中提取数据并将其放入对象数组或对象向量中。

If you instead go the AbstractTableModel route, you would use your own data structure for the nucleus of the model, and so here, your ArrayList would work just fine, but you'd be responsible for a lot more of the heavier lifting. It's not impossible to do, but would require a little more work. You may wish to look through Rob Camick's webtip blog as it has some decent model examples. You can find it here: Java Tips Weblog. In particular, please check out it's Row Table Modelentry.

如果您改为使用 AbstractTableModel 路线,您将使用您自己的数据结构作为模型的核心,因此在这里,您的 ArrayList 可以正常工作,但您将负责更多更重的提升。这不是不可能做到,但需要更多的工作。您可能希望浏览 Rob Camick 的 webtip 博客,因为它有一些不错的模型示例。您可以在此处找到它:Java 技巧博客。特别是,请查看它的行表模型条目。