0

I've been trying to load my array into a JTable object with no luck. So here is my array:

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}

I went to http://docs.oracle.com/javase/tutorial/uiswing/components/table.html And there is no constructor for putting int arrays, but there is for subject.

Anyone know a method, thanks!

1

4 Answers 4

2

You could do something like this:

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"...});
Sign up to request clarification or add additional context in comments.

Comments

2

I see two possibilities here: zou can use Integer[][] instead of int[][] which can be casted to Object[][] and this will work with a JTable OR you can write your own data model.

Depending on what you want to achieve in the end you should choose the more appropriate one.

Comments

1

Just try changing the int array to an Integer array

Comments

1

Please try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.