How to pass an 2D array to jtable in Netbeans - java

It is my first time I create a jtable,I want to display a jtable of int from another class.So I call the method getTable and assign it to the jtable,is it right?
jTable1 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new int[][] = TableAdapter.getTableC()
));
jScrollPane1.setViewportView(jTable1);
It keeps saying arraydimension missing, then I call the method getDimension() and I inserted it in various ways
new int[getDimension()][] = TableAdapter.getTableC()
or
new int[getDimension()][new int[getDimension()][] = TableAdapter.getTableC()
Thanks in adavance, and I am using Netbeans.
I get the an animal table which has two types of animals and from this I interpret to integer code which is stored in a new table(tableC) just to make it easier
package tigers.bunnies;
public class TableAdapter {
static public int tableC[][];//=new int[3][3];
static private int dimension;
public void Table(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public static int[][] getTableC() {
return tableC;
}
public static int getDimension() {
return dimension;
}
}
also when I use
jTable1.setModel(new javax.swing.table.DefaultTableModel(
TableAdapter.getTableC()
));
it has these errors:
(C:\Users\user\Desktop\error.png)

Your getTableC method is static but your Table method, which initializes the array, is not, resulting in returning an uninitialized array. make Table method static or remove static keyword from getTableC, tableC and dimmension and make Table method a constructor.
package tigers.bunnies;
public class TableAdapter {
public int tableC[][];//=new int[3][3];
private int dimension;
public TableAdapter(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public int[][] getTableC() {
return tableC;
}
public int getDimension() {
return dimension;
}
Also, an int array is not an Object array. Change it to Integer before passing to JTable model:
TableAdapter ta = new TableAdapter();
int[][] temp = ta.getTableC();
Integer[][] Result = new Integer[temp.length][temp[0].length];
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++)
result[i][j] = new Integer(temp[i][j]);
}
Object[] header = {"Column1", "Column2"};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(result, header)

Probably your TableAdapter.getTable() method returns an array of single dimension. Also you didn't supply the table header but I don't think it's the direct cause of the exception. You should call setModel this way:
Object[] header = {"Column1", "Column2..."};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(TableAdapter.getTableC(), header)

Related

Clear multi dimensional Object in Java

I want to pass 4 arrays from a method which is in A class, to a method in B class.
I create an instance of class A in the method which is in class B to get the arrays.
The method in A class is defined as Object[] and I use:
return new Object[]{Array1,Array2,Array3,Array4};
to return the arrays.
In method of B class I get the arrays with an object defined as:
private Object outGeoObj[] = new Object[4];
I am retrieving successfully the arrays, but I want to clear the object before I use it again. I tried:
public void ClearValues(){
if (outGeoObj != null){
outGeoObj = null;
}
else{
System.out.println("Object is null");
}
}
but it doesn't work. Any suggestions?
Minimal Working Example:
Class B:
public class MainFem {
private OutGeoMesh outmesh;
private Object outGeoObj[] = new Object[4]; // [0: Xmpoint, 1: Ympoint, 2: Vec, 3: numpoints]
public MainFem() {
outmesh = new OutGeoMesh();
}
public void ClearValues(){
if (outGeoObj != null){
for(int i = 0; i < outGeoObj.length; i++) {
outGeoObj[i] = null;
}
}
else{
System.out.println("Object is null");
}
} // END Method ClearValues
public void MainStart(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel){
outGeoObj = outmesh.createOutGeomesh(Xpoint, Ypoint, nump, c2, Line, drawPanel);
int temp = (int[][]) outGeoObj[3];
System.out.println(temp[0][0]);
}// End Method MainStart
} // END CLASS MainFem
Class A:
public class OutGeoMesh {
private double Xmpoint[][][] = new double[500][200][20];
private double Ympoint[][][] = new double[500][200][20];
private double Vec[][][] = new double[500][2][20];
private int numpoints[][] = new int[500][20];
public OutGeoMesh() {
// TODO Auto-generated constructor stub
}
public Object[] createOutGeomesh(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel) {
for (int j = 0; j <= c2; j++) {
for (int i = 0; i < nump[j]; i++) {
Vec[i][0][j] = i;
Vec[i][1][j] = i+1;
Xmpoint[i][0][j] = Xpoint[i][j];
Ympoint[i][1][j] = Ypoint[i][j];
numpoints[i][j] = numpoints[i][j] + 1;
} // END FOR i
} // END FOR j
return new Object[]{Xmpoint,Ympoint,Vec,numpoints};
} // END METHOD createOutGeomesh
// ---------------------------------
} // END CLASS OutGeoMesh
You need to do something like this:
Arrays.fill(outGeoObj, null);
The reason that your code doesn't work is because you are only erasing your reference to the array, but other parts of your code are still using that same array. By using Arrays.fill you can erase the contents of the array.

How to call a constructor from main method in java?

I need to write a program to solve the eight queens problem and I have no idea how to do it, but I have already started with the multidimensional array. The thing is that I don't know how to call a constructor from the main class, just to check if the array was constructed properly, or how to call it from a method. Can anybody help, please? This is the code, it returns null.
import javax.swing.JOptionPane;
public class Eightqueens
{
private static int[][] board;
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,board);
}
public Eightqueens (int size)
{
size = 8;
board = new int[size][size];
int row;
int col;
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
board[row][col] = 0;
}
}
You are supposed to use the value passed to the constructor, not overwrite it :
...
private int[][] board;
...
public Eightqueens (int size)
{
size = 8; // remove this
...
}
public int[][] getBoard()
{
return board;
}
public static void main(String[] args)
{
Eightqueens equeens = new Eightqueens (8); // create an instance
JOptionPane.showMessageDialog(null,equeens.getBoard()); // use accessor to get
// board
}
In addition, it doesn't make sense to initialize a static variable (board) in the constructor, since each new instance you create would overwrite its value. I'd change it to non-static, and then you can get it from your instance by using an accessor method (equeens.getBoard()).
To call your constructor you must 'construct' a new object.
Eightqueens obj = new Eightqueens(5);
just when you instantiate your object of class with new keyword , you call your constructor.
like this :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}
You can start by calling your constructor by making a new instance of Eightqueens
int size = 1; // anything
new Eightqueens(size);
This code does not return null, it does not return anything. You never call your constructor :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}
You can't call your constructor again. It only runs at the start of the code.
You can however, create a new instance of it to run it again.
The Dialog Box is empty because the value of board is nothing, which is because it has not been initialized. The board get a value in the constructor method. So you have to call the constructor method before you show the dialog box.
public static void main(String[] args)
{
Eightqueens eq = new Eightqueens(8);
JOptionPane.showMessageDialog(null,board);
}
Also, in the constructor method, you are overwriting the value of size given by you earlier. Thus, there is practically no need to supply the variable to the method. So, either you remove the line:
size = 8;
or, change the constructor method to not input the value, like this:
public Eightqueens ()
{
int size = 8;
board = new int[size][size];
int row;
int col;
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
board[row][col] = 0;
}

2 separated objects are connected for some reason

This is my homework(assignment). I really hope someone can help me figure out what I did wrong.
When I tried to create an object of State
state = new State(tablesize, tb);
and then tried to make a copy
State st2 = new State(state);
and then tried to modify the data in state
state.placeNumber(1,1,3);
for some reason, the data in st2 is also changed.
Below is the code. I really hope someone can point out where my mistake is.
Thanks
public class State
{
private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];
//constructor
public State()
{
}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{
lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}
public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}
public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);
System.out.println("");
}
System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}
public int[][] gettable()
{
return table;
}
public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}
public class Dikuho extends State
{
private static State state;
public static void main(String[] args) {
int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];
/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;
//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;
//initialize the state
state = new State(tablesize, tb);
**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);
st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}
}
Your copy constructor has made a shallow copy of table 2D array. Both the original object and the copy refer to the same original array, because you assign the array reference from the original to the new object. That's fine for the int values, because the values are copied. But that's not okay for objects, for which references to the obejct are copied.
Instead of just copying the reference to the array...
table = s.gettable();
You'll need to create a new, copied array:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
public int[][] gettable()
{
return table;
}
So, both of your state objects are referencing the same array. you need to create a new array for each instance.

Java, filling Object[][] array with data

I'm trying to fill an Object[][] array with data from my Object Class. However im having problems filling the array. Below is what I am trying to do to fill the Object[][] data. at the moment the returned data variable cannot be seen by the method. I have tried removing the method and filling the array where rows in declared but cannot because there is a for loop.
Am I currently filling the object[][] array correctly?
public class CustomersDialog extends javax.swing.JDialog {
private CustomerList customers = new CustomerList();
Object rows[][] = getData();
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer = new Customer();
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
Object [][] data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
}
Further doing this method of creating the array outside the loop causes an 'empty statement message' by the compiler and it says it 'requires line ends ; after the .get statements':
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer;
Object [][] data;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
You're not doing it properly.
In your code, you're declaring an array INSIDE for loop, which means that after the loop, the array doesn't exist anymore. That's why you can't return data - it simply does not exist.
More about scope and lifetime of variables you can read there: http://www.c4learn.com/javaprogramming/the-scope-and-lifetime-of-variables-in-java-programming-language/
What you want to do is to declare array outside the loop:
Object [][] data;
for(int i; i < size; i++) {
// Filling data array
}
return data;
Next thing is that if you want to use an array, you should initialize it first:
Object [][] data = new Object [size][3];
Then you can fill it in for loop, like this:
for(int i; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i][0] = Integer.toString(customer.getCustomerID());
data[i][1] = customer.getfName();
data[i][2] = customer.getlName();
}
You have to allocate the array in two times. Once for the rows, and after once per row.
Object[][] data = new Object[size];
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i] =
new Object[]{
Integer.toString(customer.getCustomerID()),
customer.getfName(),
customer.getlName()
};
}
If you really want to use a 2 dimensional Array than you must define the size of the Array first (also if it is a n dimensional Array!)
See this content to get some clarification:
http://www.leepoint.net/notes-java/data/arrays/arrays-2D.html
It seems to me like you only have one size Parameter for the Array, so I would use a normal Array instead of a 2 dimensional one.
I would do something like this:
public Object[] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Object[] result = new Object[size];
Customer customer;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
result[i] = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
If you have to use a 2 dimensional Object Array, than you have to define the second size dimension and fill the array like this:
for(int i = 0; i < sizeDimOne; i++) {
for(int k = 0; k < sizeDimTwo; k++) {
result[i][k] = { { Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
}
Hope this is helpful.

Converting an ArrayList into a 2D Array

In Java how do you convert a ArrayList into a two dimensional array Object[][]?
From comments: I will describe you the problem with more details: an XML file includes a list of contacts (e.g. name, address...). The only way I can obtain this information is through an ArrayList, which will be given to me. As I need to store the content of this array list in a Java Swing table in an ordered manner, I was thinking to convert it into a two dimensional array of objects
I presume you are using the JTable(Object[][], Object[]) constructor.
Instead of converting an ArrayList<Contact> into an Object[][], try using the JTable(TableModel) constructor. You can write a custom class that implements the TableModel interface. Sun has already provided the AbstractTableModel class for you to extend to make your life a little easier.
public class ContactTableModel extends AbstractTableModel {
private List<Contact> contacts;
public ContactTableModel(List<Contact> contacts) {
this.contacts = contacts;
}
public int getColumnCount() {
// return however many columns you want
}
public int getRowCount() {
return contacts.size();
}
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0: return "Name";
case 1: return "Age";
case 2: return "Telephone";
// ...
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
Contact contact = contacts.get(rowIndex);
switch (columnIndex) {
case 0: return contact.getName();
case 1: return contact.getAge();
case 2: return contact.getTelephone();
// ...
}
}
}
Later on...
List<Contact> contacts = ...;
TableModel tableModel = new ContactTableModel(contacts);
JTable table = new JTable(tableModel);
The simple way is to add a method to the Contact like this:
public Object[] toObjectArray() {
return new Object[] { getName(), getAddress, /* ... */ };
}
and use it like this:
ArrayList<Contact> contacts = /* ... */
Object[][] table = new Object[contacts.size()][];
for (int i = 0; i < contacts.size(); i++) {
table[i] = contacts.get(i).toObjectArray();
}
Try this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
int[][] a = new int[list.size()][list.size()];
for(int i =0; i < list.size(); i++){
for(int j =0; j <list.size(); j++){
a[i][j]= list.get(j +( list.size() * i));
}
}
I managed to find "a way" to do so, knowing the number of attributes each contacts has (6). So considering an ArrayList listofContacts
int numberOfContacts = listofContacts.size()/6;
Object[][] newArrayContent = new Object[numberOfContacts][6];
for(int x = 0; x<numberOfContacts; x++){
for(int z = 0; z < 6; z++){
int y = 6 * x;
newArrayContent [x][z] = list.get(y+z);
System.out.println(newArrayContent [x][z].toString());
}
}
What you really want is to sort the ArrayList. To do that your Contacts class must implement a Comparator method.
Check the next page for an example: http://www.java-examples.com/sort-java-arraylist-descending-order-using-comparator-example
I will recommend that you parse your XML into java objects and store the object in a custom data object. This will make it easier for you to do many operations on the available data.
Here is small tutorial on how to do it.
public static String[][] convertListIntoArrayObj(List<TeamMenuSelected> possibilities) {
int numberOfColums = 2;
int numberOfRows = possibilities.size();
String[][] values = new String[numberOfRows][numberOfColums];
for(int x=0; x<possibilities.size(); x++) {
TeamMenuSelected item = possibilities.get(x);
values[x][0] = item.getTeamName();
values[x][1] = item.getTeamCuisine();
}
return values;
}
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("element_1");
arrayList.add("element_2");
arrayList.add("element_3");
arrayList.add("element_4");
int k=0;
int row = 2, col = 2;
Object[][] objArray = new Object[row][col];
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
objArray[i][j] = arrayList.get(k);
k++;
if(k > arrayList.size()) {
break;
}
}
}
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.println("Row no "+i+" col no "+j+" "+objArray[i][j] );
}
}
}

Categories

Resources