Data changes in JTable cell.
Hi all,
On editing a cell in a Jtable ,necessary changes must get enforced in the corresponding cells of the same JTable.For example,I have fields called Quantity ,SalePrice and TotalAmount in a Jtable,where the Quantity field is editable.When i edit the Quantity value,a calculation (Changed Quantity *SalePrice)=TotalPrice must happen .Hence the Total Amount field must get Updated now.This must occur when I edit the Quantity and press Tab.No Button action is involved.Please tell me how to do this.the JTable does not use any TableModel.Thanks in advance.
As I said in your other post, your table does have a model.
What you seem to be saying is that your table has some calculated columns. If so then you should create an explicit table model so that when a cell is update the setValueAt() method performs any calculations based on this change and updates the rest of the model.
Remember to fire the appropriate events after the change.
Similar Messages
-
hi experts
i'm tring to detect the data change in the JTable. The java.sun.com
gives one ex on this using "TableModelListener". but the program is
giving errors on using that. I want to detect the data changes
and also to save the data in its new form. how can i do it??
Also, if ur having a large table data and the user changes only one cell , do i have to write the whole table back to the database ???
Ashishhere is the code. if i write "implements TableModelListener" then
an error occurs
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TableDisplay extends JFrame implements TableModelListener{
private Connection connection;
private JTable table;
public TableDisplay()
//using JDBC to connect to a Microsoft ODBC database.
String url = "jdbc:odbc:trial";
String username = "ashish";
String password = "ashish";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
url, username, password );
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
getTable();
setSize( 500, 350 );
show();
private void getTable()
Statement statement;
ResultSet resultSet;
try {
String query = "SELECT * FROM shippers";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
private void displayResultSet( ResultSet rs )
throws SQLException
// position to first record
boolean moreRecords = rs.next();
// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
validate();
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
/* switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
currentRow.addElement( rs.getString( i ) );
return currentRow;
public void shutDown()
try {
connection.close();
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
public static void main( String args[] )
final TableDisplay app = new TableDisplay();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
app.shutDown();
System.exit( 0 ); -
Way to listen for change in JTable cell?
I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
Currently, I can only get control of the application once the user has left the cell they are editing.
Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....If you want to know when the contents of a cell have been updated you should use a TableModelListener.
If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table. -
Start or stop edit jtable cell editing
Hello,
I got a problem with the jtable DefaultModel isCellEditable.
If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
private class MouseClickHandler extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
int no_mouseclick = 0;
no_mouseclick = event.getClickCount();
if (no_mouseclick >= 2) {
int cur_row = 0;
cur_row = table.getSelectedRow();
// table.setColumnSelectionAllowed(true);
// table.setRowSelectionAllowed(true);
for (int i=0;i<table.getColumnCount();i++){
table.editCellAt(cur_row,i);
System.out.println("mouse row--->" + cur_row);
I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
Could anyone of you out there provide some hints please
ThanksHello,
Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
Could someone provide the hint please
Thank -
JTable = Cell Alignment
Is it possible to centre align data in a JTable cell? If possible, where can I see how to do so.
ThxHere's an article that should help:
http://www-106.ibm.com/developerworks/java/library/j-jtable/index.html?dwzone=java -
Hi all,
Is it possible to keep track the cell focus change in JTable so that I can perform appropriate validation. For example, user use the key to move from cell (2,3) to (2,4) or use the mouse to move from (2,4) to (5,3).
I know that it is possible to use ListSelectionEvent on SelectionModel (for row change) and & ColumnModel (for change change) to do that. However, when both row & column change simultaneously, I need to do only 1 validation (in fact, the validation must have both information). My existing code gives me two separate event instead.
Any idea ? Thanks in advance.This will be a decently hard nut to crack without making a slightly (or worse) cluttered solution.
I've been part of a framework where applications-developer has requested solutions like you currently ask for. The solution we implemented was twofold.
1) We made an centralised TableModel that people could use as-is or extend if nessecary. To this tablemodel we added a new set of events that could be consumed, or in some cases even replaced.
The events was for instance 'beforeCellChange' and contained enough data on the current value, the new value, location in model and space for replacing any of the above values. Many more events was added as time went by as well.
We made the event-listener fairly generalized and the type sent in the actual event, this allowed us to expand the events without having to change any interfaces. The drawback with this was that it forces the developer to check which type of event is happening, a bit like events happened in AWT 1.0.
With the help of this, the developers just added the nessecary listeners to the table model and they could consume, change, validate any input to a table before it was committed.
2) No good method for row-verification could really be found.
There was a few futile tries, but since data could be entered in any order, the validation raised the amount of code with a order of magnitude. It does work, by listening on selection events, but quite a few extra checks has to be resolved, as instance with rows not validated etc etc.
My recomendations, verify data carefully from events either from model or the table-editor. The result will most assurdly end in that you need to have an tablemodel on your own and also TableCellRenderer to accomplish all that you want to do.
Yours sincerely
Peter Norell -
How to listen a JTable cell is changed?
is it have any Listener can know the JTable cell cursor change to other?
Thanks!JTable exposes a ListSelectionModel through getSelectionModel() that you can listen to for changes in the selected row. I think you need to get the TableColumnModel to detect changes in the selected column:
table.getSelectionModel().addSelectionListener(selectionListener);
table.getColumnModel().getSelectionModel().addSelectionListener(selectionListener);selectionListener should get notified if a change is made to the selected row or column.
Hope this helps. -
I have a JTable which contains all the services charges and It should automatically calculate the Total of all the service Charges and so my client wants that on JTable Cell Change the total field should be updated
So Can any body give me the event listener for that
Thanks in advance
CSJakhariaThanks for that
That Works But do u know anything which prevents the continous loop
I mean I have to change certain fields in the JTable itself in the listner itself and if i do that it ends up in Stack Overflow Exception Which implies never ending loop
I can stop that with the use of variable But is there any easy way out I mean any method by which i can stop this endless LOOP -
Code to change JTable cell color not working
My code below is supposed to change the color
of a single JTable cell however its not working.
Could anyone please tell me why?
Here's the code:
import java.awt.*;
import javax.swing.table.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorTable extends JTable {
public ColorTable() {
AbstractTableModel tableModel = new AbstractTableModel() {
public Class getColumnClass(int column) { return Integer.class; }
public int getColumnCount() { return 6; }
public int getRowCount() { return 10;}
public Object getValueAt(int row,int col) { return new Integer(row * col); }
setModel(tableModel);
setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
this.setRowSelectionAllowed(false);
this.setCellSelectionEnabled(true);
addMouseListener(new MouseAdapter() {
private ColorRenderer renderer;
private JColorChooser chooser = new JColorChooser();
public void mousePressed(MouseEvent e) {
if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
// chooser.setColor(renderer.getColor());
renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
class ColorRenderer extends DefaultTableCellRenderer {
private Color cellColor;
public ColorRenderer(Color color) { cellColor = color; }
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
System.out.print("row= " + row + "\n");
System.out.print("column= " + column + "\n");
System.out.print("OBJECT VALUE=" + value.toString());
//Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
if (isSelected) {
setOpaque(true);
setBackground(cellColor);
else {
setBackground(Color.white);
setForeground(Color.black);
return this;
public void setColor(Color color)
cellColor = color;
ColorTable.this.repaint();
public Color getColor() { return cellColor; }
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
ColorTable table = new ColorTable();
panel.add(table);
frame.getContentPane().add(panel);
frame.setSize(500,250);
frame.setVisible(true);My code below is supposed to change the color
of a single JTable cell however its not working.
Could anyone please tell me why?
Here's the code:
import java.awt.*;
import javax.swing.table.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorTable extends JTable {
public ColorTable() {
AbstractTableModel tableModel = new AbstractTableModel() {
public Class getColumnClass(int column) { return Integer.class; }
public int getColumnCount() { return 6; }
public int getRowCount() { return 10;}
public Object getValueAt(int row,int col) { return new Integer(row * col); }
setModel(tableModel);
setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
this.setRowSelectionAllowed(false);
this.setCellSelectionEnabled(true);
addMouseListener(new MouseAdapter() {
private ColorRenderer renderer;
private JColorChooser chooser = new JColorChooser();
public void mousePressed(MouseEvent e) {
if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
// chooser.setColor(renderer.getColor());
renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
class ColorRenderer extends DefaultTableCellRenderer {
private Color cellColor;
public ColorRenderer(Color color) { cellColor = color; }
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
System.out.print("row= " + row + "\n");
System.out.print("column= " + column + "\n");
System.out.print("OBJECT VALUE=" + value.toString());
//Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
if (isSelected) {
setOpaque(true);
setBackground(cellColor);
else {
setBackground(Color.white);
setForeground(Color.black);
return this;
public void setColor(Color color)
cellColor = color;
ColorTable.this.repaint();
public Color getColor() { return cellColor; }
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
ColorTable table = new ColorTable();
panel.add(table);
frame.getContentPane().add(panel);
frame.setSize(500,250);
frame.setVisible(true); -
How to change a selected cell background color in JTable?
Hi all,
I am trying to change the background color of a selected cell by clicking on that particular cell. DefaultTableCellRenderer class provides setBackground(Color c) to change the background color of unselected cells. Is there a way to change a selected cell background color?
Thank you,
ArthurWrite your own renderer (eg. extending DefaultTableRenderer) and put in getTableCellRendererComponent method something like this:
if( isSelected && hasFocus )
setBackground( Color.RED );
setForeground( Color.GREEN );
} -
Can not show the JCheckBox in JTable cell
I want to place a JCheckBox in one JTable cell, i do as below:
i want the column "d" be a check box which indicates "true" or "false".
String[] columnNames = {"a","b","c","d"};
Object[][] rowData = {{"", "", "", Boolean.FALSE}};
tableModel = new DefaultTableModel(rowData, columnNames);
dataTable = new JTable(tableModel);
dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
I do not understand it, can you help me?
Thank you very much!
coral9527Do not use DefaultTableModel, create your own table model and you should implement the method
getColumnClass to display the boolean as checkbox ...
I hope the following colde snippet helps you :
class MyModel extends AbstractTableModel {
private String[] columnNames = {"c1",
"c2"};
public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
public int getColumnCount() {
//System.out.println("Calling getColumnCount");
return columnNames.length;
public int getRowCount() {
//System.out.println("Calling row count");
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.
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) {
data[row][col] = value;
fireTableCellUpdated(row, col); -
How to get the data from a table cell
Could somebody suggest me how I can get the data value from a table cell if I set that cell a Double object previously.
Thanks very muchThanks for camickr's information.
And thanks uhrand,
I haven't got it sloved. I am sick on this problem.
I have the methods to let the table editable. My tableModel code is from Sun Tutorial.
It has the code like this:
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 < 1) {
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();
public 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]);
System.out.println();
System.out.println("--------------------------");
} -
Hello everyone,
I dont have a whole lot of experience w/ JTables and this problem has been troubling me for a while now. I have a JTable that significantly changes when the user hits the calculate button, so instead of going through the trouble of completely reformatting the table by adding/removing columns and table headers, I simple make a new model and set the table's model to the new one, and then call table.updateUI(). The problem is that my custom cell renderer that displays a down or up arrow depending on how the given column is sorted stops working. The sorter works properly and the table displays properly, but the arrows do not change from up to down or vise versa when a column is resorted. The whole process works just fine the first time, but the more times the user pushes the calculate button the more off it gets. I have added a flag in the actionPerformed method in my cell renderer that tells me when the table header is clicked. Every time the calculate button is hit, more flags appear when the table header is clicked. Therefore the arrows change position on odd numbers and do not on evens (because the evens cancel eachother out and the arrow appears to sit still), however the sorter still works properly. It seems as though somehow a new mouse listener or cell renderer is added after each time the calculate button is pressed. Either that or the entire table is not being reset somehow and something is still invisible in the background.
Here is some of my code.
// The initial table with no data
String[] str = {"class 1", "class 2", "class 3", "class 4", "class 5", "= GPA"};
String[][] data= {{"", "", "", "", "", ""},
pmModel = new ProjectionModel(str, data);
mainTable = new JTable(pmModel);
mainTable.getTableHeader().setDefaultRenderer(new SortButtonRenderer());
// After the calculate button has been pushed:
// The table is reset here. TableSorter extends TableMap
ProjectionModel newModel = new ProjectionModel(courseList, charList);
TableSorter sorter = new TableSorter(newModel);
// this method is shown below
sorter.addMouseListenerToHeaderInTable(mainTable);
sorter.sortedUp = false;
mainTable.addNotify();
mainTable.setModel(sorter);
// SortButtonRenderer extends TableCellRenderer
SortButtonRenderer renderer = new SortButtonRenderer();
mainTable.getTableHeader().setDefaultRenderer(renderer);
// set the arrow to DOWN on the first column
renderer.setSelectedColumn(0);
renderer.setSelectedColumn(0);
mainTable.updateUI();
// This is the addMouseListenerToTable(JTable table) found in the TableSorter class
public void addMouseListenerToHeaderInTable(JTable table) {
final TableSorter sorter = this;
final JTable tableView = table;
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (e.getClickCount() == 1 && column != -1) {
SortButtonRenderer renderer =
(SortButtonRenderer)tableView.getTableHeader().getDefaultRenderer();
//int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
//boolean ascending = (shiftPressed == 0);
boolean ascending = (renderer.getLastColumn() == column && !sortedUp);
renderer.setLastColumn(column);
sorter.sortByColumn(column, ascending);
if (ascending) sortedUp = true;
else sortedUp = false;
renderer.setSelectedColumn(column);
// the flag that prints the column that is pressed
System.out.println(column + " " + sortedUp);
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener); // it seems like i need a way to remove any
// previous mouseListeners here, i think this would solve the problem
}The flag's output looks something like this:
< first time calculate button is clicked >
< column 0 is clicked> 0 false
< column 0 is clicked again > 0 true
< second time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
notice they cancel eachother out so the arrow stays in the same position
< third time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
0 false
notice they dont cancel eachother out, so the arrow changes positions
This problem is really bugging me. I appreciate any help. Thanks.
-kcWell I fixed my problem but I kind of cheated...
I used a static variable in the class that inits the GUI to keep track of the MouseListeners that are added to the table headers by the TableSorter. In the TableSorter class's addMouseListenerToTableHeader(JTable table) class I added a line of code before the "th.addMouseListener(listListener)" line: "th.removeMouseListener(Projector.lastListener))"
It works but it kind of sucks. If there is a better way to do it that would be great. I'm sorry if you read through all of that stuff and then I ended up fixing my own problem anyway :(
Thanks anyway.
-kc -
Problem in event handling of combo box in JTable cell
Hi,
I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
I get the following exception,
Exception occurred during event dispatching:
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Can any one tell me how to over come this problem.
Thanks,
RaghuHere's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
Hope this helps.
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* 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();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
} -
Update JTable cells via setValueAt
Hello all,
I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
When trying to change the a value in the table I get these errors:
"Exception occurred during event dispatching:
java.lang.ClassCastException: java.lang.String
at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
at javax.swing.JTable.getValueAt(JTable.java:1711)
at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
public void setValueAt(Object avalue, int r, int c){
if(r < cache.size()){
row[c] = (Object[])cache.set(r, avalue);
fireTableCellUpdated(r, c);
}//setValueAt
*********For reference here's the getValueAt method*************************
public Object getValueAt(int r, int c){
if(r < cache.size()){
row = (Object[])cache.get(r);
return row[c];
else
return null;
}//getValueAtI would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
I don't think its anything to do with setValueAt.
I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
Good luck [email protected]
Hello all,
>
I'm trying to implement a setValueAt method using an
arrayList.....no success.What listeners should I have
set up(For JTable or my table model)? I am new at
this and I'm trying to update the JTable cells after a
query from some db. Could anyone help?
When trying to change the a value in the table I get
these errors:
"Exception occurred during event dispatching:
java.lang.ClassCastException: java.lang.String
at
CachingResultSetTableModel.getValueAt(CachingResultSetT
bIleModel.java:37)
at javax.swing.JTable.getValueAt(JTable.java:1711)
at
javax.swing.JTable.prepareRenderer(JTable.java:3530)"
public void setValueAt(Object avalue, int r, int c){
if(r < cache.size()){
row[c] = (Object[])cache.set(r, avalue);
fireTableCellUpdated(r, c);
}//setValueAt
*********For reference here's the getValueAt
method*************************
public Object getValueAt(int r, int c){
if(r < cache.size()){
row = (Object[])cache.get(r);
return row[c];
else
return null;
}//getValueAt
Maybe you are looking for
-
What do I need to get in order for my Apple TV to work with my TV? My TV only has 1 HDMI port and this cable is plugged into my cable box. Thank you in advance
-
What's happening when I change tempo?
I have some audio tracks that have been chopped into regions. The regions are butted up to one another. They are pieces from different tracks that have been put together. I noticed that if I change the tempo in the transport window, I end up either w
-
How can I install my iMac's Aperture on my MacBrookPro
How can I install my iMac's Aperture on my MacBrookPro
-
IMac has few display options, any way to enable more?
This is my uncle's iMac () and there are a lack of options for resolution. He's running @ 1920x1200 but the next level down is 1344x840. Is there any way to enable more resolutions between those 2, as it seems like a fairly big drop in resolution set
-
Is there a way to find out the content of texts on my daughter's phone?
We have a daughter with special needs who is trying very hard to be independent. I don't worry about her as much as I worry what others say to her. I try to monitor daily what she is texting and what others are texting to her. I have a pretty good ha