将数组加载到 Java 表

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

Load an array to a Java table

javajtable

提问by Gabriel A. Zorrilla

This is driving me crazy. I read the Sun's tutorial regarding the creation of a basic table with a default data model, but cant figure out a simple example about how to load an array of data-objects like:

这真让我抓狂。我阅读了有关使用默认数据模型创建基本表的 Sun 教程,但无法找出有关如何加载数据对象数组的简单示例,例如:

class dataObject{
String name;
String gender;
Byte age;

public dataObject (String name, String gender, Byte age){
   this.name = name;
   .
   .

}

Then i create, for example, a vector of this stuff:

然后我创建,例如,这个东西的向量:

Vector v = new Vector(99);

v.addElement(new dataObject("Marrie", "Female", 33);
v.addElement(new dataObject("John", "Male", 32);

With dataObject i'd gather the info, now how the heck i show it in a table? Because this is not working:

使用 dataObject 我会收集信息,现在我如何在表格中显示它?因为这不起作用:

JTable newTable = new Jtable(v, header) // header is another Vector.

I'm getting some errors that lead me to this last line. So, any help, even little, is apreciated. I know there are several threads about this, but those people already have a gasp about how JTable + TableModel works, I just barely get it.

我收到了一些错误,导致我进入最后一行。因此,任何帮助,即使很少,都值得赞赏。我知道有几个关于此的主题,但那些人已经对 JTable + TableModel 的工作原理感到震惊,我只是勉强理解。

Thanks a lot.

非常感谢。

采纳答案by akf

There are two ways you can create a JTable with a basic, prepared dataset:

有两种方法可以使用基本的准备好的数据集创建 JTable:

  1. a 2D Objectarray
  2. a Vectorwhose elements are Vector
  1. 二维Object数组
  2. 一个Vector其元素Vector

so you can do this:

所以你可以这样做:

 Object [][] model = {{"Marrie", "Female","33"},{"John","Male","32"}};
 JTable table = new JTable(model);

or you could do this:

或者你可以这样做:

 Vector model = new Vector();
 Vector row = new Vector();

 row.add("Marrie");
 row.add("Female");
 row.add("33");
 model.add(row);

 row = new Vector();
 row.add("John");
 row.add("Male");
 row.add("32");
 model.add(row);

 JTable table = new JTable(model);

The next step would be to implement your own TableModelto utilize the DataObjectclass that you have put together (note that Java classes start with caps). Extending AbstractTableModelmakes life easy, as you only need to implement three methods to get started:

下一步是实现您自己的TableModel以利用DataObject您组合在一起的类(请注意,Java 类以大写字母开头)。扩展AbstractTableModel让生活变得轻松,因为您只需要实现三种方法即可开始:

public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);

the first two are easy, you can get the size of your Vectorfor row count and hard-code the val for column count. getValueAtis where you pull the data from your DataObject

前两个很简单,您可以获取Vector行数的大小并硬编码列数的 val。 getValueAt是你从你的数据中提取数据的地方DataObject

Here is an example using an anonymous class, extending AbstractTableModel.

这是一个使用匿名类的示例,扩展AbstractTableModel.

final Vector<DataObject> myDataObjects = new Vector<DataObject>();
myDataObjects.add(...);// add your objects
JTable table = new JTable(new AbstractTableModel() {

    public int getRowCount() {return myDataObjects.size();}
    public int getColumnCount() { return 3; }
    public Object getValueAt(int row, int column){
         switch (column) {
           case 0:
              return myDataObjects.get(row).getName();
           case 1:
              return myDataObjects.get(row).getGender();
           case 2:
              return myDataObjects.get(row).getAge();
           default:
              return "";
         }
    }
});

I have kept the Vectorso as to keep it close to your current implementation. You can easily change that to an ArrayList in this example without any worries.

我保留了Vector以使其接近您当前的实现。在本示例中,您可以轻松地将其更改为 ArrayList,而无需担心。

回答by dsmith

I've never used JTable before, but the documentation says that the constructor takes a "Vector of Vectors" as the first parameter, and not a Vector of dataObjects.

我以前从未使用过 JTable,但文档说构造函数将“向量的向量”作为第一个参数,而不是数据对象的向量。

回答by camickr

You can't load data objects into the DefaultTableModel. You need to create a custom TableModel to do this. The Bean Table Modelis such a model that can make this process easier for you.

您不能将数据对象加载到 DefaultTableModel 中。您需要创建一个自定义 TableModel 来执行此操作。该豆表型号是这样一种模式,可以使这个过程变得更容易。

回答by OscarRyz

The problem is, the constructor you're using was designed to hold a vector which holds other vectors.

问题是,您使用的构造函数旨在保存一个包含其他向量的向量。

Each one with the information.

每一张都有资料。

See this working sample to understand it better:

请参阅此工作示例以更好地理解它:

import javax.swing.*;
import java.util.Vector;

public class TableDemo {
    public static void main( String [] args ){
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();

        Vector<Object> row = new Vector<Object>();
        row.add( "Marie");
        row.add( "Female");
        row.add( 33);
        data.add(row);

        Vector<Object> otherRow = new Vector<Object>();
        otherRow.add( "John");
        otherRow.add( "Male");
        otherRow.add( 32 );
        data.add(otherRow);

        Vector<String> headers = new Vector<String>();
        headers.add("Name");
        headers.add("Gender");
        headers.add( "Age");


        JTable table = new JTable( data, headers );

        JFrame frame = new JFrame();
        frame.add( new JScrollPane( table ));
        frame.pack();
        frame.setVisible( true ); 

    }
}

Which creates:

这创造了:

something like this http://img695.imageshack.us/img695/2032/capturadepantalla201006r.png

像这样 http://img695.imageshack.us/img695/2032/capturadepantalla201006r.png

Just in case, you should take a look at this:

以防万一,你应该看看这个:

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

If you haven't done yet.

如果你还没有完成。

回答by arooaroo

I know a lot of people can be wary of including yet another jar file, but to be honest, no matter how simple the JTable (or JList or JComboBox), I always utilise the GlazedListslibrary. Quite frankly it's one of the most amazing libs you'll ever use. It's very, very flexible. But a simple example consists of putting your beans into a special list called EventList. Then construct a table format; create the model by binding the format to the data list, and then set as the table's model.

我知道很多人可能会担心包含另一个 jar 文件,但老实说,无论 JTable(或 JList 或 JComboBox)多么简单,我总是使用GlazedLists库。坦率地说,它是您使用过的最神奇的库之一。它非常非常灵活。但是一个简单的例子是将您的 bean 放入一个名为 EventList 的特殊列表中。然后构造表格格式;通过将格式绑定到数据列表来创建模型,然后设置为表的模型。

Assume you have a Person class:

假设你有一个 Person 类:

public class Person {
  private String firstName;
  private String surname;
  private int age;

  ... standard constructors, getters and setters...
}

Now, to make your table display a list of these people:

现在,让您的表格显示这些人的列表:

EventList<Person> peopleEventList = new BasicEventList<Person>();
peopleEventList.add(... create some objects and add it the usual way ...);
...

String[] columnProperties = { "firstName", "surname", "age" };
String[] columnLabels = { "First name", "Surname", "Age" };
TableFormat personTableFormat = GlazedLists.tableFormat(columnProperties, columnLabels);
EventTableModel personTableModel = new EventTableModel(peopleEventList, personTableFormat);
myJTable.setModel(personTableModel);

I'm writing this from memory, but I think it's more or less correct. The great thing with using this library is it's seriously easy to add sorting and filtering to the table. Get the basic table working first, then start looking on the GlazedLists site to see what else you can do. There are some really good screencaststoo.

我是凭记忆写的,但我认为这或多或少是正确的。使用这个库的好处是可以非常容易地向表中添加排序和过滤。首先让基本表工作,然后开始在 GlazedLists 站点上查看您还可以做什么。还有一些非常好的截屏视频

PS I'm in no way affiliated with this library, I simply think it rocks!

PS 我与这个图书馆没有任何关系,我只是觉得它很酷!