Reputation: 701
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!
Upvotes: 0
Views: 2105
Reputation: 10943
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);
}
Upvotes: 1
Reputation: 675
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.
Upvotes: 2
Reputation: 46219
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"...});
Upvotes: 2