This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Refresh JTable with New data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Refresh JTable with New data" Watch "Refresh JTable with New data" New topic
Author

Refresh JTable with New data

Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
I have an test application, with a textbox and a button for accepting a string to search for within a MS Access table. It displaying the matching record results in a JTable. The problem is the Information is getting read and will only display if I click on the table first. I have included the complete code below. Note: this is test code only I have hacked together a few different examples.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableTest extends JFrame
{
protected JTable m_table;
protected StockTableData m_data;
protected JLabel m_title;
private JPanel panel12;
private JTextField txtName;
private JButton cmdQuery;


public TableTest() {

// Frame Caption
super("Table Test");
setSize(600, 300);
m_data = new StockTableData();

// TestField and JButton
panel12 = new JPanel();
panel12.setLayout(new BoxLayout(panel12, BoxLayout.X_AXIS));
panel12.add(Box.createRigidArea(new Dimension(25,0)));
txtName = new JTextField(10);
panel12.add( txtName );
panel12.add(Box.createRigidArea(new Dimension(34,0)));
cmdQuery = new JButton("Query");
cmdQuery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Dean2;
Dean2 = txtName.getText();
m_data.retrieveData( Dean2 );
System.out.println("Error");
m_table.repaint();
}
});
panel12.add( cmdQuery );
getContentPane().add(panel12, BorderLayout.NORTH);


m_table = new JTable();
m_table.setAutoCreateColumnsFromModel(false);
m_table.setModel(m_data);


for (int k = 0; k < StockTableData.m_columns.length; k++) {<br /> DefaultTableCellRenderer renderer = new <br /> ColoredTableCellRenderer();<br /> renderer.setHorizontalAlignment(<br /> StockTableData.m_columns[k].m_alignment);<br /> TableColumn column = new TableColumn(k, <br /> StockTableData.m_columns[k].m_width, renderer, null);<br /> m_table.addColumn(column); <br /> }<br /> JTableHeader header = m_table.getTableHeader();<br /> header.setUpdateTableInRealTime(true);<br /> header.addMouseListener(m_data.new ColumnListener(m_table));<br /> header.setReorderingAllowed(true);<br /> m_table.getColumnModel().addColumnModelListener(<br /> m_data.new ColumnMovementListener());<br /> JScrollPane ps = new JScrollPane();<br /> ps.getViewport().add(m_table);<br /> getContentPane().add(ps, BorderLayout.CENTER);<br /> WindowListener wndCloser = new WindowAdapter() {<br /> public void windowClosing(WindowEvent e) {<br /> System.exit(0);<br /> }<br /> };<br /> addWindowListener(wndCloser);<br /> setVisible(true);<br /> }<br /> public static void main(String argv[]) {<br /> new TableTest();<br /> }<br /> }<br /> <br /> class ColoredTableCellRenderer extends DefaultTableCellRenderer<br /> {<br /> public void setValue(Object value) <br /> {<br /> if (value instanceof ColorData) {<br /> ColorData cvalue = (ColorData)value;<br /> setForeground(cvalue.m_color);<br /> setText(cvalue.m_data.toString());<br /> }<br /> else if (value instanceof IconData) {<br /> IconData ivalue = (IconData)value;<br /> setIcon(ivalue.m_icon);<br /> setText(ivalue.m_data.toString());<br /> }<br /> else<br /> super.setValue(value);<br /> }<br /> }<br /> class Fraction<br /> {<br /> public int m_whole;<br /> public int m_nom;<br /> public int m_den;<br /> public Fraction(double value) {<br /> int sign = value <0 ? -1 : 1;<br /> value = Math.abs(value);<br /> m_whole = (int)value;<br /> m_den = 32;<br /> m_nom = (int)((value-m_whole)*m_den);<br /> while (m_nom!=0 && m_nom%2==0) {<br /> m_nom /= 2;<br /> m_den /= 2;<br /> }<br /> if (m_whole==0)<br /> m_nom *= sign;<br /> else<br /> m_whole *= sign;<br /> }<br /> public double doubleValue() {<br /> return (double)m_whole + (double)m_nom/m_den;<br /> }<br /> public String toString() {<br /> if (m_nom==0)<br /> return ""+m_whole;<br /> else if (m_whole==0)<br /> return ""+m_nom+"/"+m_den;<br /> else<br /> return ""+m_whole+" "+m_nom+"/"+m_den;<br /> }<br /> }<br /> class SmartLong<br /> {<br /> protected static NumberFormat FORMAT;<br /> static {<br /> FORMAT = NumberFormat.getInstance();<br /> FORMAT.setGroupingUsed(true);<br /> }<br /> public long m_value;<br /> public SmartLong(long value) { m_value = value; }<br /> public long longValue() { return m_value; }<br /> public String toString() { return FORMAT.format(m_value); }<br /> }<br /> <br /> class ColorData<br /> {<br /> public Color m_color;<br /> public Object m_data;<br /> public static Color GREEN = new Color(0, 128, 0);<br /> public static Color RED = Color.red;<br /> public ColorData(Fraction data) {<br /> m_color = data.doubleValue() >= 0 ? GREEN : RED;<br /> m_data = data;<br /> }<br /> public ColorData(Color color, Object data) {<br /> m_color = color;<br /> m_data = data;<br /> }<br /> <br /> public ColorData(Double data) {<br /> m_color = data.doubleValue() >= 0 ? GREEN : RED;
m_data = data;
}

public String toString() {
return m_data.toString();
}
}
class IconData
{
public ImageIcon m_icon;
public Object m_data;
public IconData(ImageIcon icon, Object data) {
m_icon = icon;
m_data = data;
}

public String toString() {
return m_data.toString();
}
}
class StockData
{
public static ImageIcon ICON_UP = new ImageIcon("ArrUp.gif");
public static ImageIcon ICON_DOWN = new ImageIcon("ArrDown.gif");
public static ImageIcon ICON_BLANK = new ImageIcon("blank.gif");
public IconData m_symbol;
public String m_name;
public Fraction m_last;
public Fraction m_open;
public ColorData m_change;
//public ColorData m_changePr;
//public SmartLong m_volume;
public StockData(String symbol, String name, double last,
double open, double change) {
m_symbol = new IconData(getIcon(change), symbol);
m_name = name;

System.out.println(m_last);
m_last = new Fraction(last);
m_open = new Fraction(open);
m_change = new ColorData(new Fraction(change));
// m_changePr = new ColorData(new Double(changePr));
// m_volume = new SmartLong(volume);
}
public static ImageIcon getIcon(double change) {
return (change>0 ? ICON_UP : (change<0 ? ICON_DOWN :
ICON_BLANK));
}
}
class ColumnData
{
public String m_title;
public int m_width;
public int m_alignment;

public ColumnData(String title, int width, int alignment) {
m_title = title;
m_width = width;
m_alignment = alignment;
}
}
class StockTableData extends AbstractTableModel
{
static final public ColumnData m_columns[] = {
new ColumnData( "Code ID", 100, JLabel.LEFT ),
new ColumnData( "Name", 160, JLabel.LEFT ),
new ColumnData( "Date", 100, JLabel.RIGHT ),
new ColumnData( "Type", 100, JLabel.RIGHT ),
new ColumnData( "Description", 100, JLabel.RIGHT ),
// new ColumnData( "Change %", 100, JLabel.RIGHT ),
// new ColumnData( "Volume", 100, JLabel.RIGHT )
};
protected SimpleDateFormat m_frm;
protected Vector m_vector;
protected java.util.Date m_date;
protected int m_columnsCount = m_columns.length;
protected int m_sortCol = 0;
protected boolean m_sortAsc = true;
protected int m_result = 0;
public StockTableData() {
m_frm = new SimpleDateFormat("MM/dd/yyyy");
m_vector = new Vector();
setDefaultData();
}
public void setDefaultData() {
try {
m_date = m_frm.parse("4/6/1999");
}
catch (java.text.ParseException ex) {
m_date = null;
}
m_vector.removeAllElements();
m_vector.addElement(new StockData("ORCL", "Oracle Corp.",
23.6875, 25.375, -1.6875));

Collections.sort(m_vector, new
StockComparator(m_sortCol, m_sortAsc));
}
public int getRowCount() {
return m_vector==null ? 0 : m_vector.size();
}
public int getColumnCount() {
return m_columnsCount;
}
public String getColumnName(int column) {
String str = m_columns[column].m_title;
if (column==m_sortCol)
str += m_sortAsc ? " �" : " �";
return str;
}

public boolean isCellEditable(int nRow, int nCol) {
return false;
}
public void setValueAt(Object value, int row, int col) {

fireTableCellUpdated(row, col);
}
public Object getValueAt(int nRow, int nCol) {
if (nRow < 0 | | nRow>=getRowCount())
return "";
StockData row = (StockData)m_vector.elementAt(nRow);

switch (nCol) {
case 0: return row.m_symbol;
case 1: return row.m_name;
case 2: return row.m_last;
case 3: return row.m_open;
case 4: return row.m_change;
//case 5: return row.m_changePr;
//case 6: return row.m_volume;
}
return "";

}

public String getTitle() {
if (m_date==null)
return "Stock Quotes";
return "Stock Quotes at "+m_frm.format(m_date);
}
public int retrieveData(String Dean) {
// GregorianCalendar calendar = new GregorianCalendar();
// calendar.setTime(date);
// int month = calendar.get(Calendar.MONTH)+1;
// int day = calendar.get(Calendar.DAY_OF_MONTH);
// int year = calendar.get(Calendar.YEAR);
//final String query = "SELECT data.symbol, symbols.name, "+
// "data.last, data.open, data.change, data.changeproc, "+
// "data.volume FROM DATA INNER JOIN SYMBOLS "+
// "ON DATA.symbol = SYMBOLS.symbol WHERE "+
// "month(data.date1)="+month+" AND day(data.date1)="+day+
// " AND year(data.date1)="+year;

final String query = "select Code_Name, Code_Name, Code_ID, Code_ID, Code_ID from Code WHERE Code_Name like '%" + Dean + "%' or Code_Description like '%" + Dean + "%' or Code like '%" + Dean + "%';";
//final String query = "select Code_Name, Code_Name, Code_ID, Code_ID, Code_ID from Code;";

//final String query = "select Code_Name, Code_Name, Code_ID, Code_ID, Code_ID from Code WHERE Code_Name like '%example%' or Code_Description like '%example%' or Code like '%example%';";
System.out.println(query);

Thread runner = new Thread() {
public void run() {
try {
// Load the JDBC-ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc dbc:Test", "admin", "");
System.out.println("Error2");
Statement stmt = conn.createStatement();
System.out.println("Error2.1");
ResultSet results = stmt.executeQuery(query);
System.out.println("Error3");
boolean hasData = false;
while (results.next()) {
if (!hasData) {
m_vector.removeAllElements();
hasData = true;
}
System.out.println("Error4");
String symbol = results.getString(1);
String name = results.getString(2);
double last = results.getDouble(3);
double open = results.getDouble(4);
double change = results.getDouble(5);
// double changePr = results.getDouble(6);
// long volume = results.getLong(7);
//m_vector.addElement(new StockData(symbol, name, last,
// open, change, changePr, volume));
System.out.println(symbol);
System.out.println(name);
System.out.println(last);
System.out.println(open);
System.out.println(change);
m_vector.addElement(new StockData(symbol, name, last,open, change));
//m_vector.addElement(symbol, name, last,open, change));
System.out.println("Error11");
}
System.out.println("Close Files");
results.close();
stmt.close();
conn.close();
if (!hasData) // We've got nothing
m_result = 1;
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Load data error: "+e.toString());
m_result = -1;
}
//m_date = date;
Collections.sort(m_vector,
new StockComparator(m_sortCol, m_sortAsc));
m_result = 0;
}
};
runner.start();
return m_result;
}
class ColumnListener extends MouseAdapter
{
protected JTable m_table;
public ColumnListener(JTable table) {
m_table = table;
}
public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = m_table.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();
if (modelIndex < 0)
return;
if (m_sortCol==modelIndex)
m_sortAsc = !m_sortAsc;
else
m_sortCol = modelIndex;
for (int i=0; i < m_columnsCount; i++) { //NEW
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
m_table.getTableHeader().repaint();
Collections.sort(m_vector, new
StockComparator(modelIndex, m_sortAsc));
m_table.tableChanged(
new TableModelEvent(StockTableData.this));
m_table.repaint();
}
}
class ColumnMovementListener implements TableColumnModelListener
{
public void columnAdded(TableColumnModelEvent e) {
m_columnsCount++;
}
public void columnRemoved(TableColumnModelEvent e) {
m_columnsCount--;
if (m_sortCol >= e.getFromIndex())
m_sortCol = 0;
}
public void columnMarginChanged(ChangeEvent e) {}
public void columnMoved(TableColumnModelEvent e) {}
public void columnSelectionChanged(ListSelectionEvent e) {}
}
}
class StockComparator implements Comparator
{
protected int m_sortCol;
protected boolean m_sortAsc;
public StockComparator(int sortCol, boolean sortAsc) {
m_sortCol = sortCol;
m_sortAsc = sortAsc;
}
public int compare(Object o1, Object o2) {
if(!(o1 instanceof StockData) | | !(o2 instanceof StockData))
return 0;
StockData s1 = (StockData)o1;
StockData s2 = (StockData)o2;
int result = 0;
double d1, d2;
switch (m_sortCol) {
case 0: // symbol
String str1 = (String)s1.m_symbol.m_data;
String str2 = (String)s2.m_symbol.m_data;
result = str1.compareTo(str2);
break;
case 1: // name
result = s1.m_name.compareTo(s2.m_name);
break;
case 2: // last
d1 = s1.m_last.doubleValue();
d2 = s2.m_last.doubleValue();
result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
break;
case 3: // open
d1 = s1.m_open.doubleValue();
d2 = s2.m_open.doubleValue();
result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
break;
case 4: // change
d1 = ((Fraction)s1.m_change.m_data).doubleValue();
d2 = ((Fraction)s2.m_change.m_data).doubleValue();
result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
break;
// case 5: // change %
// d1 = ((Double)s1.m_changePr.m_data).doubleValue();
// d2 = ((Double)s2.m_changePr.m_data).doubleValue();
// result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
// break;
// case 6: // volume
// long l1 = s1.m_volume.longValue();
// long l2 = s2.m_volume.longValue();
// result = l1<l2 ? -1 : (l1>l2 ? 1 : 0);
// break;
}
if (!m_sortAsc)
result = -result;
return result;
}
public boolean equals(Object obj) {
if (obj instanceof StockComparator) {
StockComparator compObj = (StockComparator)obj;
return (compObj.m_sortCol==m_sortCol) &&
(compObj.m_sortAsc==m_sortAsc);
}
return false;
}
}
Thanks again for any help.
Dean Reedy
bengt hammarlund
Ranch Hand

Joined: Oct 17, 2003
Posts: 78
hi there.
Try the method updateUI() found on the JComponent class.
Probably the best thing you do is call it after ALL data is added to the table.

Good luck.


<b><i>Bengt Hammarlund</i><br />� Sun Certified Java Programmer</b>
 
 
subject: Refresh JTable with New data
 
Similar Threads
Adding/Removing rows from a JTable
JTABLE getValueAt compiling error
JTable Dynamic - Urgent
Printing a Database Query
Color in JTable