Java 使用 AbstractTableModel 向 JTable 添加行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18310204/
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-08-12 00:22:43  来源:igfitidea点击:

Add row to JTable with AbstractTableModel

javaswingjtableactionabstracttablemodel

提问by Gerret

I need help at adding a empty row to my JTable. I use a AbstractTableModel for my JTable! I have here a small executable program for you so it is easier to help me.

我需要帮助将空行添加到我的 JTable。我为我的 JTable 使用了 AbstractTableModel!我这里有一个小的可执行程序供您使用,因此可以更轻松地帮助我。

Main Class - TestClass.java

主类 - TestClass.java

package testproject;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTable;

public class TestClass {

    String[] header = {"Name", "Quantity"};
    ArrayList<Object[]> data = new ArrayList<Object[]>();

    public TestClass() {
        data.add(new Object[]{"Apple", "234"});
        data.add(new Object[]{"Banana", "123"});
        data.add(new Object[]{"Cranberry", "346"});

        JFrame frame = new JFrame();
        JTable table = new JTable(new Model(data, header));
        JMenuBar menubar = new JMenuBar();
        JMenu editmenu = new JMenu("Edit");

        Action addrowaction = new AbstractAction("Add Row") {
            private static final long serialVersionUID = 1433684360133156145L;

            @Override
            public void actionPerformed(ActionEvent e) {
                data.add(new Object[9]);
            }
        };

        frame.add(table);

        frame.setJMenuBar(menubar);
        menubar.add(editmenu);
        editmenu.add(addrowaction);

        frame.setLocationByPlatform(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.pack();
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestClass();
            }
        });
    }
}

Table Model - Model.java

表模型 - Model.java

package testproject;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class Model extends AbstractTableModel{
    private static final long serialVersionUID = 6889542282067432083L;

    private String[] header;
    private ArrayList<Object[]> data;

    public Model(ArrayList<Object[]> data, String[] header) {
        this.header = header;
        this.data = data;
    }

    @Override
    public int getColumnCount() {
        return header.length;
    }

    @Override
    public String getColumnName(int column) {
        return header[column];
    }

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

    @Override
    public Object getValueAt(int row, int column) {
        return data.get(row)[column];
    }

    @Override
    public void setValueAt(Object value, int row, int column) {
        data.get(row)[column] = value;
        fireTableCellUpdated(row, column);
    }
}

Basically I want to use a Action in the edit menu to add a empty row. Please do not answer with other links! I searched for it but don't understand it or it isnt suitable for my program!

基本上我想在编辑菜单中使用一个操作来添加一个空行。请不要用其他链接回答!我搜索了它但不明白它或它不适合我的程序!

EDIT: Updated the source as suggested by MadProgrammer! There is only one problem left. How I update the JTable so the new Row is displayed at the moment I have to resize the Window and the Table is updating!

编辑:按照MadProgrammer 的建议更新源代码!只剩下一个问题了。我如何更新 JTable 以便在我必须调整窗口大小并且表正在更新时显示新行!

  • Thank you for help
  • 谢谢你的帮助

采纳答案by trashgod

As @MadProgrammer comments, arrays are conceptually easy to understand but hard to expand & contract. Instead, use a Collection. In this example, MyModelmanages a List<Row>that is implemented as an ArrayList<Row>. Each Rowis a Plain Old Java Object (POJO) having an attribute for each column. Try adding a method to insert new rows using the constructor as an example, then try adding a column to Row. The example uses a static nested class to avoid clutter.

正如@MadProgrammer 评论的那样,数组在概念上很容易理解,但很难扩展和收缩。相反,使用Collection. 在此示例中MyModel管理List<Row>作为ArrayList<Row>. 每个Row都是一个普通的旧 Java 对象 ( POJO),每列都有一个属性。尝试添加一个方法以使用构造函数插入新行作为示例,然后尝试将一列添加到Row. 该示例使用静态嵌套类来避免混乱。