您可以将带有 int、double 或只是字符串的数据添加到 JTable 中吗

Can you add data with int,double or just string to a JTable

我是 Java 的新手。我主要做C#。我正在查看下面 link 上的示例:

A Simple JTable Example for Display

但是在创建包含 int、double、boolen 和字符串的二维数组时出现错误。错误显示 "Type mismatch cannot convert from int to object"。这是否意味着此示例显示的方式不正确?我正在使用 Eclipse Juno。任何帮助将不胜感激

这是代码: TableExample.java

package net.codejava.swing;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class TableExample extends JFrame 
{
public TableExample()
{
    //headers for the table
    String[] columns = new String[] {
        "Id", "Name", "Hourly Rate", "Part Time"
    };

    //actual data for the table in a 2d array
    Object[][] data = new Object[][] {
        {1, "John", 40.0, false },
        {2, "Rambo", 70.0, false },
        {3, "Zorro", 60.0, true },
    };

    //create table with data
    JTable table = new JTable(data, columns);

    //add the table to the frame
    this.add(new JScrollPane(table));

    this.setTitle("Table Example");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    this.pack();
    this.setVisible(true);
}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new TableExample();
        }
    });
}   
} 

你能检查一下你 运行ning 的 java 版本吗?我是 运行ning 版本 7,代码编译对我来说很好。我也能看到输出。在版本 5 之前的 java 版本中,原始数据类型(如 int、float 到 类 Integer、Float 的自动装箱分别需要用户自己完成。您可以尝试通过以下方式 redeclare/redefine 数据并再次 运行 您的程序:-

Object[][] data = new Object[][] {
    {new Integer(1), new String("John"), new Float(40.0), new Boolean(false) },
    {new Integer(2), new String("Rambo"), new Float(70.0), new Boolean(false) },
    {new Integer(3), new String("Zorro"), new Float(60.0), new Boolean(true) },
};