Java Swing | 扩展 AbstractTableModel 并将其与 JTable 一起使用 | 几个问题

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

Java Swing | extend AbstractTableModel and use it with JTable | several questions

javaswingjtableabstracttablemodel

提问by JavaHater

I followed Oracle's model for implementing an AbstractTableModel

我遵循 Oracle 的模型来实现 AbstractTableModel

http://download.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java

http://download.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java

I did this because my table has to contain 3 columns, and the first has to be a JCheckBox.

我这样做是因为我的表必须包含 3 列,第一列必须是 JCheckBox。

Here's my code:

这是我的代码:

public class FestplattenreinigerGraphicalUserInterfaceHomePagePanelTableModel extends AbstractTableModel {
private String[] columnNames = {"Auswahl",
                                    "Dateiname",
                                    "Pfad"};
    private Object[][] data = {
    {new Boolean(true), "datei.tmp",
     "/home/user/tmp"}
    };

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        return data[row][col];
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

     public boolean isCellEditable(int row, int col) {
        if (col == 0) {
            return true;
        } else {
            return false;
        }
    }

     public void setValueAt(Object value, int row, int col) {            
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }

}

}

Here are my questions:

以下是我的问题:

  1. How does JTable (new JTable(FestplattenreinigerGraphicalUserInterfaceHomePagePanelTableModel)) know what the column names are and their values are? Since there's no contructor in my AbstractTableModel?! Is it becaue columnNames and data must be named like they are and JTable accesses them?
  2. How can i put new Values in my JTable? Since columnNames and data are arrays. Can i replace them with vectors? If so, how do I init these vectors? In a constructor in myAbsTableModel?
  1. JTable ( new JTable(FestplattenreinigerGraphicalUserInterfaceHomePagePanelTableModel))如何知道列名是什么以及它们的值是什么?因为我的 AbstractTableModel 中没有构造函数?!是不是因为 columnNames 和 data 必须像它们一样命名并且 JTable 访问它们?
  2. 如何在 JTable 中放入新值?由于 columnNames 和 data 是数组。我可以用向量代替它们吗?如果是这样,我如何初始化这些向量?在 myAbsTableModel 的构造函数中?

I think it's very easy to get a solution but this Table handling isn't trivial to me, so thank u very much!

我认为找到解决方案很容易,但这个表格处理对我来说并不简单,所以非常感谢你!

回答by camickr

All Swing components come with default model implementations. I suggest you understand how to use them first before trying to create your own. For a JTable its called the DefaultTableModel. Read the API for methods to dynamically add/remove rows of data from the model. Here is a simple example to get you started:

所有 Swing 组件都带有默认模型实现。我建议您在尝试创建自己的之前先了解如何使用它们。对于 JTable,它称为 DefaultTableModel。阅读 API 以了解从模型中动态添加/删除数据行的方法。这是一个让您入门的简单示例:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableBasic extends JPanel
{
    public TableBasic()
    {
        String[] columnNames = {"Date", "String", "Integer", "Boolean"};

        Object[][] data =
        {
            {new Date(), "A", new Double(1), Boolean.TRUE },
            {new Date(), "B", new Double(2), Boolean.FALSE},
            {new Date(), "C", new Double(9), Boolean.TRUE },
            {new Date(), "D", new Double(4), Boolean.FALSE}
        };

        JTable table = new JTable(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers and editors to be used based on Class

            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                        return o.getClass();
                }

                return Object.class;
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("TableBasic");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TableBasic() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

回答by Valentin Rocher

First, I think you need to learn a bit more about Java, especially inheritance (I'm referencing your constructor problem.

首先,我认为您需要更多地了解 Java,尤其是继承(我指的是您的构造函数问题。

Answers to your questions :

回答您的问题:

  • define your column names via a private final staticattribute, assuming your column names don't change.
  • since your class extends AbstractTableModel, you can define a constructor for it, where you'll pass the data. Redefine the getValueAtmethod to allow the model to use the data you're passing.
  • 通过private final static属性定义您的列名,假设您的列名没有改变。
  • 由于您的类 extends AbstractTableModel,您可以为它定义一个构造函数,您将在其中传递数据。重新定义getValueAt方法以允许模型使用您传递的数据。

Some more advice :

还有一些建议:

  • don't do what you're doing in getColumnClass. Normally, all elements in a column will have the same class, so do a switchon the column index to get the classes.
  • to add a JCheckBoxin one of your columns, you'll have to use a custom TableCellRenderer
  • 不要做你正在做的事情getColumnClass。通常,列中的所有元素都具有相同的类,因此switch在列索引上执行 a以获取类。
  • JCheckBox在其中一列中添加 a ,您必须使用自定义TableCellRenderer

回答by Jeff Knecht

  1. The JTable determines how many columns by calling getColumnCount() on your column model. It then iterates and calls getColumnName(idx) for each column. Your class tells it the column name -- look at your implementation of those methods.

  2. You can store your data in whatever format you want. The JTable calls methods on your table model to retrieve that data. If you want to add new items to your model, you can implement an addItem(Object o) method to your model; just be sure to call fireTableRowsInserted() for each new item.

  1. JTable 通过在您的列模型上调用 getColumnCount() 来确定有多少列。然后它为每一列迭代并调用 getColumnName(idx)。你的类告诉它列名——看看你对这些方法的实现。

  2. 您可以以任何您想要的格式存储您的数据。JTable 调用表模型上的方法来检索该数据。如果要向模型添加新项目,可以对模型实施 addItem(Object o) 方法;一定要为每个新项目调用 fireTableRowsInserted() 。