java 如何设置 JTable 动态的行和列

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

How to set rows and columns of a JTable Dynamic

javaswingjtablerowsdynamic-columns

提问by Lalo Galicia

my question is how to set dynamic, the number of rows and columns in a JTable? I mean if the user wants to create a table of 2 rows and 2 columns, he just type down the number. How can I do that, I've tried with the DefaultModel with no success.

我的问题是如何动态设置 JTable 中的行数和列数?我的意思是如果用户想要创建一个 2 行 2 列的表格,他只需输入数字。我该怎么做,我已经尝试过使用 DefaultModel 但没有成功。

I will appreciate any help.

我将不胜感激任何帮助。

Thanks

谢谢

回答by MadProgrammer

DefaultTableModelhas two means by which you can define the number of rows/columns at runtime.

DefaultTableModel有两种方法可以在运行时定义行/列数。

You could...

你可以...

Simply create a new DefaultTableModel, passing it the rows and columns you want...

只需创建一个 new DefaultTableModel,将您想要的行和列传递给它...

DefaultTableModel model = new DefaultTableModel(rows, cols);

and then apply this to the JTable. This will, obviously, replace the existing table model, meaning you will lose all of it's data.

然后将其应用于JTable. 显然,这将替换现有的表模型,这意味着您将丢失所有数据。

You could...

你可以...

Create an master DefaultTableModeland apply it to the JTableand simply use

创建一个母版DefaultTableModel并将其应用到JTable并简单地使用

model.setRowCount(rows);
model.setColumnCount(cols);

to dynamically update the number of rows and columns as required. This will allow you to preserve the data within the table model (expect when you remove rows or columns, then it's lost)

根据需要动态更新行数和列数。这将允许您保留表模型中的数据(预计当您删除行或列时,它会丢失)

Runnable example

可运行示例

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTable table;
        private DefaultTableModel model;
        private JSpinner fldRows;
        private JSpinner fldColumns;

        public TestPane() {

            setLayout(new BorderLayout());

            fldRows = new JSpinner(new SpinnerNumberModel(1, 1, 999999, 1));
            fldColumns = new JSpinner(new SpinnerNumberModel(1, 1, 999999, 1));

            JPanel options = new JPanel(new GridBagLayout());
            options.add(new JLabel("Rows: "));
            options.add(fldRows);
            options.add(new JLabel("Columns: "));
            options.add(fldColumns);

            JButton update = new JButton("Update");
            options.add(update);

            update.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int rows = (int) fldRows.getValue();
                    int cols = (int) fldColumns.getValue();

                    // Dynamic master model...
//                  model.setRowCount(rows);
//                  model.setColumnCount(cols);

                    // Replace model
                    table.setModel(new DefaultTableModel(rows, cols));
                }
            });

            model = new DefaultTableModel();
            table = new JTable();
            add(new JScrollPane(table));
            add(options, BorderLayout.NORTH);

        }

    }

}

For more details, see...

有关更多详细信息,请参阅...