0

我一直试图将我的数组加载到一个 JTable 对象中,但没有成功。所以这是我的数组:

int[][] board = {
    {0, 0, 0, 0, 2, 0, 0, 0, 0},
    {0, 0, 5, 0, 0, 0, 0, 2, 4},      
    {1, 0, 0, 4, 0, 0, 0, 3, 8},
    {0, 0, 0, 6, 0, 0, 0, 0, 7},
    {0, 0, 4, 5, 3, 8, 9, 0, 0},
    {8, 0, 0, 0, 0, 7, 0, 0, 0},
    {7, 4, 0, 0, 0, 6, 0, 0, 1},
    {6, 1, 0, 0, 0, 0, 3, 0, 0},
    {0, 0, 0, 0, 9, 0, 0, 0, 0}

我去了http://docs.oracle.com/javase/tutorial/uiswing/components/table.html 并且没有用于放置 int 数组的构造函数,但有用于主题。

谁知道方法,谢谢!

4

4 回答 4

2

你可以这样做:

Integer[][] board = new Integer[][]{
        {0, 0, 0, 0, 2, 0, 0, 0, 0},
        {0, 0, 5, 0, 0, 0, 0, 2, 4},      
        {1, 0, 0, 4, 0, 0, 0, 3, 8},
        {0, 0, 0, 6, 0, 0, 0, 0, 7},
        {0, 0, 4, 5, 3, 8, 9, 0, 0},
        {8, 0, 0, 0, 0, 7, 0, 0, 0},
        {7, 4, 0, 0, 0, 6, 0, 0, 1},
        {6, 1, 0, 0, 0, 0, 3, 0, 0},
        {0, 0, 0, 0, 9, 0, 0, 0, 0}};

new JTable(board, new String[]{"columnName1"...});
于 2012-10-30T12:11:30.043 回答
2

我在这里看到了两种可能性: zou 可以使用Integer[][]而不是int[][]可以转换为Object[][],这将与 JTable 一起使用,或者您可以编写自己的数据模型。

根据您最终想要实现的目标,您应该选择更合适的一个。

于 2012-10-30T12:14:04.660 回答
1

只需尝试将int数组更改为Integer数组

于 2012-10-30T12:14:19.293 回答
1

请试试这个

import javax.swing.*;
import java.awt.*;
public class JTableComponent{
  public static void main(String[] args) 
{
  new JTableComponent();
  }

  public JTableComponent(){
  JFrame frame = new JFrame("Creating JTable Component Example!");
  JPanel panel = new JPanel();
  Integer[][] board = {
            {0, 0, 0, 0, 2, 0, 0, 0, 0},
            {0, 0, 5, 0, 0, 0, 0, 2, 4},      
            {1, 0, 0, 4, 0, 0, 0, 3, 8},
            {0, 0, 0, 6, 0, 0, 0, 0, 7},
            {0, 0, 4, 5, 3, 8, 9, 0, 0},
            {8, 0, 0, 0, 0, 7, 0, 0, 0},
            {7, 4, 0, 0, 0, 6, 0, 0, 1},
            {6, 1, 0, 0, 0, 0, 3, 0, 0},
            {0, 0, 0, 0, 9, 0, 0, 0, 0}};

   String col[] = {"1","2","3","4","5","6","7","8","9"};
  JTable table = new JTable(board,col);
  panel.add(table,BorderLayout.CENTER);

frame.add(panel);
  frame.setSize(800,500);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
于 2012-10-30T12:16:50.457 回答