• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JTable Dynamic - Urgent

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does anyone have any example or anywhere I can go to get info. I need to make my JTable populate from a click of a button. But as my application loads, my JTable has to be created and the data should be empty. After the user clicks a button "load" the JTable data gets populated and when a click another button "clear" the JTable data gets erased. I really need any help. Thanks.
 
bob morkos
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

This is what I'm trying to do, but it's not working properly. Does anybody have any idea why it's not functionning.
<code>
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class TableModelExample3 extends JFrame {
AbstractTableModel model;
private static int i=0;
private static JPanel pnlView;
//private static JTable tbl;
public TableModelExample3(String title) {
super(title);
/*
model = new AbstractTableModel() {
// The table data
String[] columnNames = {
"Pizza", "Ordered?"
};
Object[][] data = {

{ ("Hot & Spicy" + i), Boolean.FALSE },
};

public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return data[0].length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public Class getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (value instanceof Boolean && columnIndex == 1) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
}
};
*/
//tbl = new JTable(model);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.RELATIVE;
pnlView = new JPanel();
//pnlView.add(new JScrollPane(tbl));
c.gridx=1; c.gridy=0;
getContentPane().add(pnlView, c);
JPanel pnlButton = new JPanel();
JButton btnLoad = new JButton();
btnLoad.setText("Load");
JButton btnClear = new JButton();
btnClear.setText("Clear");
pnlButton.add(btnLoad);
pnlButton.add(btnClear);
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClearActionPerformed(evt);
}
});

c.gridx=2; c.gridy=0;
getContentPane().add(pnlButton, c);

//System.out.println(model.getValueAt(0,0));
}
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
model = new AbstractTableModel() {
// The table data
Object[][] data = {
{ ("Hot & Spicy" + i), Boolean.FALSE },
{ ("Cheese" + i), Boolean.FALSE },
{ ("Ham" + i), Boolean.FALSE },
{ ("New Yorker" + i), Boolean.FALSE },
{ ("Vegetarian" + i), Boolean.FALSE }
};

String[] columnNames = {
"Pizza", "Ordered?"
};
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return data[0].length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public Class getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (value instanceof Boolean && columnIndex == 1) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
}
};
JTable tbl = new JTable(model);
pnlView.removeAll();
pnlView.add(new JScrollPane(tbl));
}
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
model = new AbstractTableModel() {
// The table data
Object[][] data = {
};

String[] columnNames = {
"Pizza", "Ordered?"
};
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return data[0].length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public Class getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (value instanceof Boolean && columnIndex == 1) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
}
};
JTable tbl = new JTable(model);
}
public static void main(String[] args) {
JFrame f = new TableModelExample3("AbstractDataModel Example 3");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
</code>
[This message has been edited by bob, morkos (edited December 21, 2001).]
[This message has been edited by bob, morkos (edited December 21, 2001).]
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is my first table I ever created, it works by connecting to a MS Access database, which connects using ODBC connection.
Note; This code was only done to verify I could make it work, thus it should be commented and organized a little better.
The retrieveData routine section is the database call.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.sql.*;
import logfile.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
public class TableTest extends JFrame {
/**
* Description of the Field
*/
protected JTable m_table;
/**
* Description of the Field
*/
protected StorageTableData m_data;
/**
* Description of the Field
*/
protected JLabel m_title;
private JPanel panel12;
private JTextField txtName;
private JButton cmdQuery;
private logfile logName;
/**
* Constructor for the TableTest object
*/
public TableTest() {
// Frame Caption
super("Table Test");
setSize(600, 300);
m_data = new StorageTableData();
// Create ErrorLog
logName = new logfile();
// 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");
logName.write_to_log("Searching for " + Dean2);
//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 < StorageTableData.m_columns.length; k++) {
DefaultTableCellRenderer renderer = new
ColoredTableCellRenderer();
renderer.setHorizontalAlignment(
StorageTableData.m_columns[k].m_alignment);
TableColumn column = new TableColumn(k,
StorageTableData.m_columns[k].m_width, renderer, null);
m_table.addColumn(column);
}
JTableHeader header = m_table.getTableHeader();
header.setUpdateTableInRealTime(true);
header.addMouseListener(m_data.new ColumnListener(m_table));
header.setReorderingAllowed(true);
m_table.getColumnModel().addColumnModelListener(
m_data.new ColumnMovementListener());
JScrollPane ps = new JScrollPane();
ps.getViewport().add(m_table);
getContentPane().add(ps, BorderLayout.CENTER);
WindowListener wndCloser =
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}

/**
* Description of the Method
*
*@param argv Description of Parameter
*/
public static void main(String argv[]) {
new TableTest();
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColoredTableCellRenderer extends DefaultTableCellRenderer {

/**
* Sets the value attribute of the ColoredTableCellRenderer object
*
*@param value The new value value
*/
public void setValue(Object value) {
super.setValue(value);
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StorageData {

/**
* Description of the Field
*/
public String m_symbol;
/**
* Description of the Field
*/
public String m_name;
/**
* Description of the Field
*/
public String m_date;
/**
* Description of the Field
*/
public String m_type;
/**
* Description of the Field
*/
public String m_description;

/**
* Constructor for the StorageData object
*
*@param symbol Description of Parameter
*@param name Description of Parameter
*@param date Description of Parameter
*@param type Description of Parameter
*@param description Description of Parameter
*/
public StorageData(String symbol, String name, String date,
String type, String description) {
m_symbol = symbol;
m_name = name;
m_date = date;
m_type = type;
m_description = description;
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnData {

/**
* Description of the Field
*/
public String m_title;
/**
* Description of the Field
*/
public int m_width;
/**
* Description of the Field
*/
public int m_alignment;

/**
* Constructor for the ColumnData object
*
*@param title Description of Parameter
*@param width Description of Parameter
*@param alignment Description of Parameter
*/
public ColumnData(String title, int width, int alignment) {
m_title = title;
m_width = width;
m_alignment = alignment;
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StorageTableData extends AbstractTableModel {

/**
* Description of the Field
*/
public final static 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),
};
/**
* Description of the Field
*/
protected SimpleDateFormat m_frm;
/**
* Description of the Field
*/
protected Vector m_vector;
/**
* Description of the Field
*/
protected java.util.Date m_date;
/**
* Description of the Field
*/
protected int m_columnsCount = m_columns.length;
/**
* Description of the Field
*/
protected int m_sortCol = 0;
/**
* Description of the Field
*/
protected boolean m_sortAsc = true;
/**
* Description of the Field
*/
protected int m_result = 0;

/**
* Constructor for the StorageTableData object
*/
public StorageTableData() {
m_frm = new SimpleDateFormat("MM/dd/yyyy");
m_vector = new Vector();
setDefaultData();
}

/**
* Sets the defaultData attribute of the StorageTableData object
*/
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 StorageData("ORCL", "Oracle Corp.",
// 23.6875, 25.375, -1.6875));

Collections.sort(m_vector, new
StockComparator(m_sortCol, m_sortAsc));
}

/**
* Sets the valueAt attribute of the StorageTableData object
*
*@param value The new valueAt value
*@param row The new valueAt value
*@param col The new valueAt value
*/
public void setValueAt(Object value, int row, int col) {
fireTableCellUpdated(row, col);
}

/**
* Gets the rowCount attribute of the StorageTableData object
*
*@return The rowCount value
*/
public int getRowCount() {
return m_vector == null ? 0 : m_vector.size();
}

/**
* Gets the columnCount attribute of the StorageTableData object
*
*@return The columnCount value
*/
public int getColumnCount() {
return m_columnsCount;
}

/**
* Gets the columnName attribute of the StorageTableData object
*
*@param column Description of Parameter
*@return The columnName value
*/
public String getColumnName(int column) {
String str = m_columns[column].m_title;
if (column == m_sortCol) {
str += m_sortAsc ? " �" : " �";
}
return str;
}

/**
* Gets the cellEditable attribute of the StorageTableData object
*
*@param nRow Description of Parameter
*@param nCol Description of Parameter
*@return The cellEditable value
*/
public boolean isCellEditable(int nRow, int nCol) {
return false;
}

/**
* Gets the valueAt attribute of the StorageTableData object
*
*@param nRow Description of Parameter
*@param nCol Description of Parameter
*@return The valueAt value
*/
public Object getValueAt(int nRow, int nCol) {
if (nRow < 0 | | nRow >= getRowCount()) {
return "";
}
StorageData row = (StorageData) m_vector.elementAt(nRow);
switch (nCol) {
case 0:
return row.m_symbol;
case 1:
return row.m_name;
case 2:
return row.m_date;
case 3:
return row.m_type;
case 4:
return row.m_description;
}
return "";
}

/**
* Gets the title attribute of the StorageTableData object
*
*@return The title value
*/
public String getTitle() {
if (m_date == null) {
return "Dean's Tester";
}
return "No date " + m_frm.format(m_date);
}

/**
* Description of the Method
*
*@param Dean Description of Parameter
*@return Description of the Returned Value
*/
public int retrieveData(String Dean) {
final String query = "select Code_ID, Code_Name, Code_Date, Type_Name, Code_Description from Code,Type WHERE (Code_Name like '%" + Dean + "%' or Code_Description like '%" + Dean + "%' or Code like '%" + Dean + "%') and Code_Type_Seq_id=Type_Seq_id;";
System.out.println(query);
Thread runner =
new Thread() {
public void run() {
Connection conn;
Statement stmt;
ResultSet results;
try {
// Load the JDBC-ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(
"jdbc dbc:Test", "admin", "");
System.out.println("Error2");
stmt = conn.createStatement();
System.out.println("Error2.1");
results = stmt.executeQuery(query);
System.out.println("Error3");
boolean hasData = false;
m_vector.removeAllElements();
while (results.next()) {
if (!hasData) {
hasData = true;
}
System.out.println("Error4");
String symbol = results.getString(1);
String name = results.getString(2);
DateFormat dateFormatter;
Locale currentLocale = new Locale("en", "US");
dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, currentLocale);
String date = dateFormatter.format(results.getDate(3));
String type = results.getString(4);
String change = results.getString(5);
m_vector.addElement(new StorageData(symbol, name, date, type, change));
System.out.println("Error11");
}
System.out.println("Close Files");
results.close();
stmt.close();
conn.close();
fireTableStructureChanged();
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;
}
finally {
Collections.sort(m_vector,
new StockComparator(m_sortCol, m_sortAsc));
m_result = 0;
}
}
};
runner.start();
return m_result;
}

/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnListener extends MouseAdapter {
/**
* Description of the Field
*/
protected JTable m_table;

/**
* Constructor for the ColumnListener object
*
*@param table Description of Parameter
*/
public ColumnListener(JTable table) {
m_table = table;
}

/**
* Description of the Method
*
*@param e Description of Parameter
*/
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(StorageTableData.this));
m_table.repaint();
}
}

/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class ColumnMovementListener implements TableColumnModelListener {
/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnAdded(TableColumnModelEvent e) {
m_columnsCount++;
}

/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnRemoved(TableColumnModelEvent e) {
m_columnsCount--;
if (m_sortCol >= e.getFromIndex()) {
m_sortCol = 0;
}
}

/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnMarginChanged(ChangeEvent e) { }

/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnMoved(TableColumnModelEvent e) { }

/**
* Description of the Method
*
*@param e Description of Parameter
*/
public void columnSelectionChanged(ListSelectionEvent e) { }
}
}
/**
* Description of the Class
*
*@author DAREEDY
*@created November 30, 2001
*/
class StockComparator implements Comparator {

/**
* Description of the Field
*/
protected int m_sortCol;
/**
* Description of the Field
*/
protected boolean m_sortAsc;

/**
* Constructor for the StockComparator object
*
*@param sortCol Description of Parameter
*@param sortAsc Description of Parameter
*/
public StockComparator(int sortCol, boolean sortAsc) {
m_sortCol = sortCol;
m_sortAsc = sortAsc;
}

/**
* Description of the Method
*
*@param o1 Description of Parameter
*@param o2 Description of Parameter
*@return Description of the Returned Value
*/
public int compare(Object o1, Object o2) {
if (!(o1 instanceof StorageData) | | !(o2 instanceof StorageData)) {
return 0;
}
StorageData s1 = (StorageData) o1;
StorageData s2 = (StorageData) o2;
int result = 0;
result = s1.m_symbol.compareTo(s2.m_symbol);
if (!m_sortAsc) {
result = -result;
}
return result;
}

/**
* Description of the Method
*
*@param obj Description of Parameter
*@return Description of the Returned Value
*/
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;
}
}

Let me know, if you need anything else.
Dean
 
bob morkos
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have solved my problem by adding a refresh into my panel code. It works fine now. Thanks. By the way, how do I make my columns stay as there displayed. I don't want the user to drag my columns and change the order, for functionality reasons.
pnlView.updateUI();
 
bob morkos
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by bob, morkos:
I have solved my problem by adding a refresh into my panel code. It works fine now. Thanks. By the way, how do I make my columns stay as there displayed. I don't want the user to drag my columns and change the order, for functionality reasons.
<code>
pnlView.removeAll();
pnlView.add(new JScrollPane(tbl1));
pnlView.updateUI();


</code>
Tip: whenever you put code, try to indent in the following way:
< c o d e > // should be declaced with no spaces
your code here. This would make your code more readable for others.
< / c o d e > // should be declaced with no spaces
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey try my code also...
<pre>
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Test12 extends JFrame implements ActionListener{
JButton add;
int i=1;
Vector rows=new Vector();
Vector cols=new Vector();
JTable table;
DefaultTableModel model;
public Test12() {
super("JTable");

add=new JButton("Add");

add.addActionListener(this);
JPanel panel1=new JPanel();
panel1.add(add);

cols.add("Comp Name");

model=new DefaultTableModel(rows,cols);
table=new JTable(model);
JScrollPane tableScrollPane=new JScrollPane(table);

Container content=getContentPane();
content.setLayout(new GridLayout(2,1));
content.add(panel1);
content.add(tableScrollPane);
Vector v=new Vector();

setSize(300,300);
setVisible(true);
}

public void actionPerformed(ActionEvent ae){
JButton actionButton=(JButton)ae.getSource();

if(actionButton==add) {
Vector temp=new Vector();
temp.add("C-"+ i++);
model.addRow(temp);
}
}

public static void main(String args[]) {
new Test12().addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
</pre>
Bhupendra Mahajan

[This message has been edited by Mahajan Bhupendra (edited December 28, 2001).]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic