Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Jtable repaint - it just doesn't work! tried

Reply
Thread Tools

Jtable repaint - it just doesn't work! tried

 
 
stan k.
Guest
Posts: n/a
 
      11-07-2003
here's the code... you'll need the libraries to get it to run so email
me if you want to try it out...

I've tried everything as you can see . . . why doesn't the table
refresh ?
the data is in there because when i retrieve the cell data it comes
out correct....
and don't talk to me about the 'fire' events because i'm already
trying several of them - several times over!

i've tried all kinds of stuff...
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();//redraws the whole table
scrollPane.repaint();
jTable1.repaint();
model.fireTableStructureChanged();
model.fireTableDataChanged();

etc . . .

does calling a repaint or fire event more than once cause a problem?

i can clean it up once i've gotten it to work but for now i am trying
anything...

as you can see i'm using the SortTable model from the sun tutorial...


import java.sql.*;
import javax.sql.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;

public class Select2Array5 extends javax.swing.JFrame {
private boolean DEBUG = false;
private javax.swing.JButton btn1; private javax.swing.JButton btn2;
private javax.swing.JButton btn3; private javax.swing.JButton btn4;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JTable jTable1;
private javax.swing.JTextArea txta1;
private javax.swing.JScrollPane scrollPane;
private TableSorter sorter;

public Select2Array5() {initComponents();}

class clsRetVals{
public String[][] myarray;
public int numRows;
public int numCols;
}

/////////////////////////////////////////////////////////////////////
class MyTableModel extends AbstractTableModel {
private String[] columnNames={"First Name","Last Name","Sport","# of
Years","Vegetarian"};
private Object[][] data = {
{"Mary", "Campione", "Snowboarding", new Integer(5), new
Boolean(false)},
{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath", "Knitting", new Integer(2), new
Boolean(false)},
{"Sharon", "Zakhour", "Speed reading", new Integer(20), new
Boolean(true)},
{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
};

public int getColumnCount() {return columnNames.length;}
public int getRowCount() {return data.length;}
public String getColumnName(int col) {return columnNames[col];}
public Object getValueAt(int row, int col) {return data[row][col];}

/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {return getValueAt(0,
c).getClass();}
// Don't need to implement this method unless your table's editable.

public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant, no matter where the
cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}

// Don't need to implement this method unless your table's data can
change.

public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at "+row+","+col +" to "+value+"
(an instance of "+value.getClass()+")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}

private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}//for()
System.out.println();
}//for()
System.out.println("--------------------------");
}
}
//////////table model///////////////////////////////////////////////////////////////


public clsRetVals rs2array(ResultSet rs){
clsRetVals retvals = new clsRetVals();
try{
rs.last();
int numRows = rs.getRow();
System.out.println("numRows base zero="+numRows);
rs.beforeFirst();
// Get the number of columns in rs
ResultSetMetaData rsmd = rs.getMetaData ();
// Get the number of columns in the result set
int numCols = rsmd.getColumnCount ();
System.out.println("numCols base zero="+ numCols); // Get the
number of columns
// Display column headings
System.out.print("the column names are: ");
for (int i=1; i<=numCols; i++) {
if (i > 1) System.out.print(",");
System.out.print(rsmd.getColumnLabel(i));
}
System.out.println("\n");
String[][] myarray = new String[numRows][numCols];
rs.first();

for (int r=0; r < numRows; r++){
System.out.print("assigning col data to array row: ");
for (int c=0; c < numCols; c++){
System.out.print(c);
myarray[r][c] = rs.getString(c+1);// note the string casting
}//c
System.out.println("\nnext row "+(r+1));
rs.next();
}//r

rs.close();
retvals.myarray=myarray;
retvals.numRows=numRows;
retvals.numCols=numCols;

// at this point i should have all my data in an array - let's
see...
/* for (int r=0; r < numRows; r++){
for (int c=0; c < numCols; c++){
System.out.print("rc:"+r+c+myarray[r][c]);
}//c
System.out.println("\n");
}//r
*/
// return the array
return retvals;
}catch (SQLException sqle) {
String[][] emptydummy=new String [0][0];
retvals.myarray=emptydummy;
retvals.numRows=0;
retvals.numCols=0;
return retvals;
}
}////////////////////////// rs2array() end


//////////rs2table///////////////////////////////////////////////////
public static void rs2table(ResultSet rs, JTable jTable1){
// takes a sql result set (vb recordset) - puts it into a 2d dyn
array, then plugs it into a jTable

//resultset position changers:
try{
rs.last();// points to last record (ie: recordcount)
//rs.first(); // gets first record

// Get the rows in rs
int numRows = rs.getRow();
System.out.println("numRows base zero="+numRows);
rs.beforeFirst();// use this when you need to reset so that the
next call will point to the first record

// Get the number of columns in rs
ResultSetMetaData rsmd = rs.getMetaData ();
// Get the number of columns in the result set
int numCols = rsmd.getColumnCount ();
System.out.println("numCols base zero="+ numCols); // Get the
number of columns

// Display column headings
System.out.print("the column names are: ");
for (int i=1; i<=numCols; i++) {
if (i > 1) System.out.print(",");
System.out.print(rsmd.getColumnLabel(i));
}
System.out.println("\n");

String[][] myarray = new String[numRows][numCols];

rs.first(); // use first here note beforeFirst...

for (int r=0; r < numRows; r++){
System.out.print("assigning col data to array row: ");
for (int c=0; c < numCols; c++){
System.out.print(c);
myarray[r][c] = rs.getString(c+1);// note the string casting
}//c
System.out.println("\nnext row "+(r+1));
rs.next();
}//r

rs.close();

System.out.println("\ndata assigned. discarding recordset. plugging
array into jTable");

jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"10", "11", null}
},
new String [] {
"col1", "col2", "col3"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Object.class,
java.lang.String.class
};

public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
/*
jTable1.setModel(new javax.swing.table.DefaultTableModel(
myarray, new String [] { "col1", "col2", "col3", "col4","c5","c6" }
));

*/
// at this point i should have all my data in an array - let's
see...
for (int r=0; r < numRows; r++){
for (int c=0; c < numCols; c++){
System.out.print("rc:"+r+c+myarray[r][c]);
}//c
System.out.println("\n");
}//r

}catch (SQLException sqle) {
}

}////////////////////////// rs2table() end
//////////rs2SystemOut///////////////////////////////////////////////////
public static void rs2SystemOut(ResultSet rs){
// takes a sql result set (vb recordset) - puts it into a 2d dyn
array, then plugs it into a jTable

//resultset position changers:
try{
rs.last();// points to last record (ie: recordcount)
//rs.first(); // gets first record

// Get the rows in rs
int numRows = rs.getRow();
System.out.println("numRows base zero="+numRows);
rs.beforeFirst();// use this when you need to reset so that the
next call will point to the first record

// Get the number of columns in rs
ResultSetMetaData rsmd = rs.getMetaData ();
// Get the number of columns in the result set
int numCols = rsmd.getColumnCount ();
System.out.println("numCols base zero="+ numCols); // Get the
number of columns

// Display column headings
System.out.print("the column names are: ");
for (int i=1; i<=numCols; i++) {
if (i > 1) System.out.print(",");
System.out.print(rsmd.getColumnLabel(i));
}
System.out.println("\n");

String[][] myarray = new String[numRows][numCols];

rs.first(); // use first here note beforeFirst...

for (int r=0; r < numRows; r++){
System.out.print("assigning col data to array row: ");
for (int c=0; c < numCols; c++){
System.out.print(c);
myarray[r][c] = rs.getString(c+1);// note the string casting
}//c
System.out.println("\nnext row "+(r+1));
rs.next();
}//r

rs.close();

System.out.println("\ndata assigned. discarding recordset. printing
array contents");

// at this point i should have all my data in an array - let's
see...
for (int r=0; r < numRows; r++){
for (int c=0; c < numCols; c++){
System.out.print("rc:"+r+c+myarray[r][c]);
}//c
System.out.println("\n");
}//r

}catch (SQLException sqle) {
}

}////////////////////////// rs2systemout() end
/////////////////////////////////////////////////////
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
txta1 = new javax.swing.JTextArea();
btn1 = new javax.swing.JButton();btn2 = new javax.swing.JButton();
btn3 = new javax.swing.JButton();btn4 = new javax.swing.JButton();
getContentPane().setLayout(new
org.netbeans.lib.awtextra.AbsoluteLayout());
setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);
setTitle("populate table with array data");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
getContentPane().add(jComboBox1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(160, 20, 240, 20));
// note this code needs TableSorter and TableMap java classes to be
compiled for
// this to work and compile properly
sorter = new TableSorter(new MyTableModel()); //ADDED THIS
jTable1 = new JTable(sorter); //NEW
sorter.addMouseListenerToHeaderInTable(jTable1); //ADDED THIS
//jTable1.setPreferredScrollableViewportSize(new Dimension(500,
70));
jTable1.setBorder(new javax.swing.border.LineBorder(new
java.awt.Color(0, 0, 0)));
jTable1.setCellSelectionEnabled(true);

//Set up tool tips for column headers.
jTable1.getTableHeader().setToolTipText("Click to sort; Shift-Click
to sort in reverse order");
//Create the scroll pane and add the table to it.
scrollPane = new JScrollPane(jTable1);
//Add the scroll pane to this panel.
// note i add the scroll pane with the table in it not the table
here..
// the scroll pane allows scrollbars to appear for the table
getContentPane().add(scrollPane, new
org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, 420, 150));
btn1.setAction(btn1.getAction());
btn1.setText("btn1 rs2array to system out");
btn1.setActionCommand(btn1.getActionCommand());
btn1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn1MouseClicked(evt);
}
});

getContentPane().add(btn1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(450, 10, -1, -1));
txta1.setLineWrap(true);
txta1.setRows(;
txta1.setTabSize(1);
txta1.setWrapStyleWord(true);
getContentPane().add(txta1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(190, 80, 500, 160));
btn2.setText("btn2 rs2SystemOut");
btn2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn2MouseClicked(evt);
}
});
getContentPane().add(btn2, new
org.netbeans.lib.awtextra.AbsoluteConstraints(170, 50, -1, -1));
btn3.setText("btn3 qry 2 textbox");
btn3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn3MouseClicked(evt);
}
});
getContentPane().add(btn3, new
org.netbeans.lib.awtextra.AbsoluteConstraints(60, 30, -1, -1));
btn4.setText("btn4 rs2array to table");
btn4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
}
});
btn4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn4MouseClicked(evt);
}
});
getContentPane().add(btn4, new
org.netbeans.lib.awtextra.AbsoluteConstraints(420, 40, -1, -1));
pack();
}

/////////////button 1 click rs2array
private void btn1MouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("button1 Query&rs2array to system out");
String res=""; String dbUrl = "jdbc:mysql:///database1";
String dbClass = "com.mysql.jdbc.Driver";
String sQry = "SELECT name, owner, species, sex, birth, death FROM
pet";
try {
String newDbUrl = System.getProperty("com.mysql.jdbc.database1");
if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
dbUrl = newDbUrl;
}
//Class.forName("org.gjt.mm.mysql.Driver"); // Load database
driver
Class.forName("com.mysql.jdbc.Driver"); // note this also loads the
mysql database driver... for simple selects i can't see any difference
Connection con = DriverManager.getConnection (dbUrl);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sQry);
clsRetVals retvals=rs2array(rs);
// extract the retvals from the retval class, 2d string array, int
array with rows & cols
String[][] myarray = retvals.myarray;
int numRows = retvals.numRows;
int numCols = retvals.numCols;
// at this point i should have all my data in an array - let's
see...
for (int r=0; r < numRows; r++){
for (int c=0; c < numCols; c++){
System.out.print("rc:"+r+c+myarray[r][c]);
}//c
System.out.println("\n");
}//r

rs.close();
con.close();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}// try-catch-catch

}
///////end of//////button 1 click

///////////////////////////// button 2 mouse click - do query, call
rs2systemOut
private void btn2MouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("btn2 Query&rs2SystemOut");
String res = "";
String dbUrl = "jdbc:mysql:///database1";
String dbClass = "com.mysql.jdbc.Driver";
String sQry = "SELECT name, owner, species, sex, birth, death
FROM pet";

try {
String newDbUrl = System.getProperty("com.mysql.jdbc.database1");
if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
dbUrl = newDbUrl;
}
//Class.forName("org.gjt.mm.mysql.Driver"); // Load database
driver
Class.forName("com.mysql.jdbc.Driver"); // note this also loads the
mysql database driver... for simple selects i can't see any difference
Connection con = DriverManager.getConnection (dbUrl);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sQry);
rs2SystemOut(rs);
rs.close();
con.close();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}// try-catch-catch

}// button 2 mouse click
///////////////////////////////////////////////////////////////////////////

/////////////////button three query & push to txtbox/////////////////
private void btn3MouseClicked(java.awt.event.MouseEvent evt) {
// Add your handling code here:
String res="";
String dbUrl = "jdbc:mysql:///database1";
String dbClass = "com.mysql.jdbc.Driver";
String sQry = "SELECT * FROM pet ORDER BY species"; // note the
difference between perl/mysql and java/mysql with the use of *


try {

String newDbUrl = System.getProperty("com.mysql.jdbc.database1");
if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
dbUrl = newDbUrl;
}

//Class.forName("org.gjt.mm.mysql.Driver"); // Load database
driver
Class.forName("com.mysql.jdbc.Driver"); // note this also loads the
mysql database driver... for simple selects i can't see any difference
Connection con = DriverManager.getConnection (dbUrl);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sQry);
while (rs.next()) {
res = rs.getString("name")+ "|"+rs.getString("species");
txta1.setText(res);
System.out.println(res);
}
rs.close();
con.close();

}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();

}// try-catch-catch


}
/////end of ////////////button three query & push to
txtbox/////////////////

//////////////////// start of btn 4////////////////////
private void btn4MouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("btn4 Query&rs2array");
String res=""; String dbUrl = "jdbc:mysql:///database1";
String dbClass = "com.mysql.jdbc.Driver";
String sQry = "SELECT name, owner, species, sex, birth, death FROM
pet";
try {
String newDbUrl = System.getProperty("com.mysql.jdbc.database1");
if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
dbUrl = newDbUrl;
}
//Class.forName("org.gjt.mm.mysql.Driver"); // Load database
driver
Class.forName("com.mysql.jdbc.Driver"); // note this also loads the
mysql database driver... for simple selects i can't see any difference
Connection con = DriverManager.getConnection (dbUrl);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sQry);
clsRetVals retvals=rs2array(rs);
// extract the retvals from the retval class, 2d string array, int
array with rows & cols
String[][] myarray = retvals.myarray;
int numRows = retvals.numRows;
int numCols = retvals.numCols;
// at this point i should have all my data in an array - let's
see...
for (int r=0; r < numRows; r++){
for (int c=0; c < numCols; c++){
System.out.print("rc:"+r+c+myarray[r][c]);
}//c
System.out.println("\n");
}//r


System.out.println("table col count"+jTable1);
System.out.println("table col count"+jTable1.getColumnCount());
//works
btn2.setText(btn2.getText()+"x");
System.out.println(btn2.getText());

// at this point, myarray, numRows and numCols need to be plugged
into the table
scrollPane.setVisible(false);
MyTableModel model = new MyTableModel();
String[] cols={"1","2","3","4","5","6"};
model.columnNames=cols;
model.fireTableStructureChanged();
model.data=myarray;
model.fireTableDataChanged();
jTable1.repaint();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();//redraws the whole table
TableSorter sorter = new TableSorter(model); //ADDED THIS
model.fireTableStructureChanged();
model.fireTableDataChanged();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();//redraws the whole table
jTable1=null; // this step is not needed but makes it easier to
understand we are rewriting it.
jTable1 = new JTable(sorter);
jTable1.validate();
model.fireTableStructureChanged();
model.fireTableDataChanged();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();//redraws the whole table
scrollPane.repaint();
jTable1.repaint();
System.out.println("cell 1 1 = "+jTable1.getValueAt(1,1));
model.fireTableStructureChanged();
model.fireTableDataChanged();

scrollPane.revalidate();
scrollPane.repaint();
scrollPane.repaint();
jTable1.setVisible(false);
jTable1.setVisible(true);
scrollPane.setVisible(true);
scrollPane.setVisible(true);
jTable1.setBounds(100,100,100,100);
jTable1.repaint();
jTable1.revalidate();
model.fireTableStructureChanged();
model.fireTableDataChanged();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();//redraws the whole table
rs.close();
con.close();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}// try-catch-catch


// public void setValueAt(Object value, int row, int col) {
//jTable1.setBorder(new javax.swing.border.LineBorder(new
java.awt.Color(0, 100, 0)));
//System.out.println(jTable1.getColumnClass(1));
// jTable1.setValueAt("asfd", 1,1);
System.out.println("click4");
// this works but prints null when it should print an object
address...
System.out.println("table col count"+jTable1.getColumnCount());
//this works when i make it a module level variable...
//System.out.println(scrollPane);
//doesn't work - null pointer exception and access violation
//jTable1.setToolTipText("new tooltip");
//didn't work . . .
//System.out.println(new Select2Array3().jTable1.getValueAt(1,1));

}
//////////////////// end of btn 4////////////////////



private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0); }
public static void main(String args[]) { new Select2Array5().show();
}

}
 
Reply With Quote
 
 
 
 
Babu Kalakrishnan
Guest
Posts: n/a
 
      11-07-2003
stan k. wrote:
> here's the code... you'll need the libraries to get it to run so email
> me if you want to try it out...
>
> I've tried everything as you can see . . . why doesn't the table
> refresh ?


Tried everything except describe what your problem is.

If you want somebody to spot what you're doing wrong, you'll need to
post only the *relevant* portion of the code that isn't working and
mention clearly what you expect the code to do and what it currently
does. It is very unlikely that people would have the patience to wade
through 500 lines of code to figure out what the problem is.

[code snipped]

BK

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
RE;Kontki if you delete kontiki any program you loaded with it in it 'will not work I have tried it with three programs and none work anymore (if you se it just stop download) 1-Twitch Computer Support 5 04-23-2009 02:45 PM
Putting a JTable inside a JTable cell? Tivo Escobar Java 1 04-12-2007 11:09 AM
How to move data from a CSV file to a JTable, and from a JTable to a CSV file ? Tintin92 Java 1 02-14-2007 06:51 PM
Re: Just tried micoshaft corporation's windopz and it sucks 7 Computer Support 4 11-03-2006 12:57 AM
Xandros Linux....just tried it...it rocks grappletech Computer Information 1 10-06-2006 11:22 PM



Advertisments