【问题标题】:JTable - load multidimensional array into tableJTable - 将多维数组加载到表中
【发布时间】:2012-10-30 20:16:50
【问题描述】:

我一直试图将我的数组加载到一个 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 数组的构造函数,但有用于主题的构造函数。

谁知道方法,谢谢!

【问题讨论】:

标签: java swing jtable


【解决方案1】:

你可以这样做:

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"...});

【讨论】:

    【解决方案2】:

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

    根据你最终想要达到的目标,你应该选择更合适的。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        请试试这个

        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);
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-10
          • 2016-03-18
          • 1970-01-01
          • 2015-11-23
          • 2013-12-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多