Jtable repaint - it just doesn't work! tried

Discussion in 'Java' started by stan k., Nov 7, 2003.

  1. stan k.

    stan k. Guest

    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[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.WindowConstants.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(8);
    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();
    }

    }
     
    stan k., Nov 7, 2003
    #1
    1. Advertising

  2. 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
     
    Babu Kalakrishnan, Nov 7, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Yoshi
    Replies:
    5
    Views:
    888
    Yoshi
    Mar 4, 2004
  2. Esko Piirainen

    repaint() call doesn't get processed

    Esko Piirainen, Nov 12, 2005, in forum: Java
    Replies:
    4
    Views:
    702
    Thomas Hawtin
    Nov 14, 2005
  3. Z
    Replies:
    12
    Views:
    4,989
    Knute Johnson
    Feb 19, 2007
  4. Kgbol
    Replies:
    4
    Views:
    1,148
  5. SamuelXiao

    repaint not work as expected

    SamuelXiao, Jan 18, 2011, in forum: Java
    Replies:
    7
    Views:
    472
    SamuelXiao
    Jan 20, 2011
Loading...

Share This Page