Whats wrong with the GUI display
Hi everyone,
I got a piece of Swing code and instead of showing the column names as One,Two,Three it shows A,B,C in the JTable!!! Can someone tell me whats wrong?
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
import java.util.*;
class TableDemo extends JPanel implements ActionListener{
//public variables
public JTable table;
public JButton button;
private Vector data=new Vector(100);
String[] columnNames={"one","two","Three"};
public final AbstractTableModel model;
public TableDemo(int totalRows,int totalCols){
super(new GridBagLayout());
model=new MyTable(totalRows,totalCols);
table=new JTable(model);
//adding the table to the scroll pane
add(new JScrollPane(table));
//adding the button and the event listener
button=new JButton("Go");
button.addActionListener(this);
add(button);
}
public void add(int rows,int cols){
for(int r=0;r<rows;r++)
for (int c=0;c<cols;c++){
data.add("Extra Hi");
}
}
//Action Event
public void actionPerformed(ActionEvent e){
for (int i=0;i<columnNames.length;i++){
data.add("Extra Hi");
}
System.out.println("someone pressed the button!");
System.out.println("Current No of Rows "+data.size()/columnNames.length);
}
//main thread
public static void main(String[] args){
JFrame frame=new JFrame();
frame.getContentPane().add(new TableDemo(10,3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.setSize(700,700);
frame.setVisible(true);
}
//this is the Abstract Model class for the Table
class MyTable extends AbstractTableModel{
//this will go in the constructor
public MyTable(int noOfRows,int noOfCols){
//gotta get the total no of elements reqd to be populated in the vector
//when we consider it as a 2D matrix
int totalNoOfElements=noOfRows*noOfCols;
for (int i=0;i<totalNoOfElements;i++){
data.add("Hi");
}
}
public void addNewRows(int row,int col){
int totalNoOfElements=row*col;
for (int i=0;i<totalNoOfElements;i++){
data.add("Extra Hi");
}
}
public int getRowCount(){
//this should be the total elements/no fo columns!Pretty simple huh?
int size=data.size()/columnNames.length;
System.out.println("Row Count:"+size);
return size;
//return data.length;
}
public int getColumnCount(){
return columnNames.length;
}
public Object getValueAt(int row,int col){
//this needs to be done for a vector now!
return (Object)data.get((row)*(col));
}
public void setValueAt(Object obj,int row,int col){
data.setElementAt(obj,(row)*(col));
fireTableCellUpdated(row,col);
}
}//inner class ends here
}//main class ends here
ciao,
Sandz
sands
__________________
Sandz
|