Updateing table model
when the complet table model is changed (numbers of colums, rows, data) is there a way to show that on screen. example:
JPane pane = new JPane;
JTable table1 = new JTable(model1);
pane.add(table);
contentPane.add(pane);
// now the mode1 is changing
model1 = model2;
//???? how to see changings in same table table1;
Vlada
call tableStructureChanged on model.
DB
Similar Messages
-
Use ComboBox TableCellEditor - values are not saved to the table model
Hi,
I got a combobox cell editor that uses to edit one of the columns.
And i got an ok button that uses to collect the data from the table and save it to the db.
In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
In this case the user think his changes were saved but the last updated field is not updated.
Is this a bug i got in the cell editor or this is the normal behaviour?
Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
private boolean isEditMode=false;
* A list of eventlisteners to call when an event is fired
private EventListenerList listenerList = new EventListenerList();
* the table model
public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
super(StbAreaMapper.clustersPriorities);
setEditMode(isEditMode);
setEditable(false);
this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setAlignmentX(Component.LEFT_ALIGNMENT);
public boolean isEditMode() {
return isEditMode;
public void setEditMode(boolean editMode) {
isEditMode = editMode;
setEnabled(editMode);
public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
int selectedIndex;
if (isSelecte) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
if(value instanceof String){
selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
setSelectedIndex(selectedIndex);
return this;
public void cancelCellEditing() {
fireEditingCanceled();
public Object getCellEditorValue() {
return getSelectedItem();
public boolean isCellEditable(EventObject anEvent) {
return isEditMode;
public boolean shouldSelectCell(EventObject anEvent) {
return false;
public boolean stopCellEditing() {
fireEditingStopped();
return true;
* Adds a new cellEditorListener to this cellEditor
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
* Removes a cellEditorListener from this cellEditor
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
* Notify all listeners that have registered interest for notification on
* this event type.
* @see javax.swing.event.EventListenerList
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
((CellEditorListener) listeners[i + 1]).editingStopped(
new ChangeEvent(this));
* Notify all listeners that have registered interest for notification on
* this event type.
* @see javax.swing.event.EventListenerList
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
}Try this
yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); -
I created a table model and use JTable to display content of a database's table with that model.
The problem is: when I update a data to data1 in a cell (first column) and hightlight another cell (second column), all cells of first column change content to data1. What 's the problem with my table model?
import java.util.Vector;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
public class CommonTableModel extends AbstractTableModel {
String[] columnNames;
Vector rows, newRow;
ResultSetMetaData metaData;
private boolean editable;
public CommonTableModel(ResultSet rs, boolean editable) {
this.editable = editable;
try {
metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
for(int column = 0; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnName(column+1);
rows = new Vector();
newRow = new Vector();
while (rs.next()) {
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement(rs.getObject(i));
rows.addElement(newRow);
} catch (SQLException ex) { System.err.println(ex);}
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return rows.size();}
public String getColumnName(int column) { return columnNames[column];}
public Object getValueAt(int row, int column) {
newRow = (Vector)rows.elementAt(row);
return newRow.elementAt(column);
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
public boolean isCellEditable(int row, int column) {
if (column == 0) { return false; }
return editable;
public void setValueAt(Object value, int row, int column) {
newRow = (Vector)(rows.elementAt(row));
newRow.setElementAt(value, column);
fireTableCellUpdated(row, column);
}Try this :
rows = new Vector();
//newRow = new Vector();
while (rs.next()) {
newRow = new Vector(); // it must be here
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement(rs.getObject(i));
rows.addElement(newRow);
}Denis -
JTable: Custom Table Model (pII)
As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
How do I create each of the following methods:
insertRow(int ow, int column)
remove row(int row)
addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
Thanks!Thanks!
I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
This is what I did:
// Letting the JTable know what each column stores and should return by
// overloading the getColumnClass() method
public Class getColumnClass(int column)
if(recordsTable.getColumnName(column) == "Ranking")
return Integer.class;
/* Why do I keep ketting an IllegalArgumentException here? *
* It keeps saying it cannot format given object as a Number */
else if(recordsTable.getColumnName(column) == "Price (�) ")
return Float.class;
else
return getValueAt(0, column).getClass();
}However, another problem has arisen.
The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
Here's the code:package Practice;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent; // for MenuItem shortcuts
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
import javax.swing.JTable; // The personally preferred GUI for this purpose
// Provides a basic implementation of TableModel
import javax.swing.table.DefaultTableModel;
// This class uses Vector to store the rows and columns of data, though
// programmer will be using LinkedLists
import java.util.LinkedList;
// User-defined classes
import Practice.MusicDatabase;
public class MusicBank extends Frame implements ActionListener
MusicDatabase mDBase;
Frame frame;
String title = "", // Frame's title
file = ""; // pathname of the file to be opened
// Declaring Menu and MenuItem variables
Menu recordM; // ...
// recordM
MenuItem newRecordR_MI, deleteRecordR_MI;
// Other irrelevant menus and sub items
DefaultTableModel recordDetails;
JTable recordsTable;
LinkedList musicList;
public MusicBank()
musicList = new LinkedList();
frame = new Frame(title);
frame.setMenuBar(menuSystem());
// Should user seek to close window externally
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
frame.dispose();
System.exit(0);
recordDetails = new DefaultTableModel();
// Creating the relevant columns
recordDetails.addColumn("Title");
recordDetails.addColumn("Identity");
recordDetails.addColumn("Music Company");
recordDetails.addColumn("Ranking");
recordDetails.addColumn("Price (�) ");
// Ensuring the table has at least one visible record (empty)
recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
// Creating the table to display the data files (music record details)
recordsTable = new JTable(recordDetails)
// Letting the JTable know what each column stores and should return by
// overloading the getColumnClass() method
public Class getColumnClass(int column)
if(recordsTable.getColumnName(column) == "Ranking")
return Integer.class;
/* Why do I keep ketting an IllegalArgumentException here? *
* It keeps saying it cannot format given object as a Number */
else if(recordsTable.getColumnName(column) == "Price (�) ")
return Float.class;
else
return getValueAt(0, column).getClass();
// Creating the menus
public MenuBar menuSystem()
MenuBar bar = new MenuBar();
// Record menu and related items
recordM = new Menu("Record");
recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));
newRecordR_MI = new MenuItem("New record");
newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
deleteRecordR_MI = new MenuItem("Delete record");
deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
recordM.add(newRecordR_MI);
recordM.addSeparator();
recordM.add(deleteRecordR_MI);
// Enabling menus with functionality
newRecordR_MI.addActionListener(this);
deleteRecordR_MI.addActionListener(this);
// Adding menus and items to menu bar
bar.add(recordM);
return bar;
public void actionPerformed(ActionEvent ae)
if(ae.getSource() == newRecordR_MI)
newRecord();
else if(ae.getSource() == deleteRecordR_MI)
deleteRecord();
// Object that will be used, in conjunction with MusicDatabase's, to
// populate the JTable
// A record in a JTable is equivalent to an element in a LinkedList
public Object[] populateRow(String title, String name, String comp, int rank, float price)
// First, update the LinkedList
mDBase = new MusicDatabase(title, name, comp, rank, price);
musicList.add(mDBase);
// Then, update the table
// As the parameters of Object tableDetails can only take a String or
// object, rank and price will have to be cast as a String and later
// parsed to their original form before use.
String rankPT = ""+rank, pricePT = ""+price;
Object rowDetails[] = {title, name, comp, rankPT, pricePT};
return rowDetails;
public static void main(String args[])
MusicBank app = new MusicBank();
// Using the platform's L&F (if Win32, Windows L&F; Mac OS, Mac OS L&F,
// Sun, CDE/Motif L&F)
// For more on this, refer to the WinHelp Java tutorial by F. Allimont
try
UIManager.getSystemLookAndFeelClassName();
catch(Exception e)
JOptionPane.showMessageDialog(app,
"Failed to create the Windows Look and Feel for this program",
"Look and Feel (L&F) error",
JOptionPane.ERROR_MESSAGE);
app.frame.setSize(500, 500);
app.frame.setVisible(true);
// Placing frame in the centre of the screen on-loading
app.frame.setLocationRelativeTo(null);
// action methods per menu items
// Also, why do I keep getting an ArrayIndexOutOfBoundsException
// here? I do know what this exception is, and how it works, but just cannot
// understand what is causing it
public void newRecord()
// Before adding a new record, check if previous record has complete
// entries. If not, either display a message (JOptionPane) or disallow
// request (simply do nothing)
// Proceed based on assesment
if(queryState() == true)
// Inform user that all entries need to be filled in before a new
// record can be created
JOptionPane.showMessageDialog(this, // current frame
"There are incomplete cells in the table."+
"\nPlease fill these in before proceeding", // Message to user
"Incomplete entries", // Title
JOptionPane.ERROR_MESSAGE); // Relevant icon
else
// To ensure that both the linked list & the table are simultaneously
// updated, JOptionPane's input dialogs are used to temporarily store
// the data which is then inputted into both (linked list and JTable)
String titleN, identityN, companyN; int rankN; float priceN;
titleN = JOptionPane.showInputDialog(this, "Enter song title");
identityN = JOptionPane.showInputDialog(this, "Enter name of singer/band");
companyN = JOptionPane.showInputDialog(this, "Enter signed/unsigned company");
rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
"Enter rank (a number)") );
System.out.println("\n JTable rows = "+recordDetails.getRowCount());
// Ensuring that the chosen rank is not already entered
/* Problem lies here */
for(int row = 1; row <= recordDetails.getRowCount(); ++row)
if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
"That number's already chosen.\nPlease enter a rank ") );
priceN = Float.parseFloat( JOptionPane.showInputDialog(this, "Finally, enter price �") );
mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
musicList.add(mDBase);
recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
priceN));
System.out.println("JTable rows after creation = "+
recordDetails.getRowCount());
// Enabling the delete record menu item (as necessary)
if((recordsTable.getRowCount()) > 0)
deleteRecordR_MI.setEnabled(true);
} // newRecord()
public void deleteRecord()
int selectedRow = recordsTable.getSelectedRow();
recordDetails.removeRow(selectedRow);
// Removing the element from the LinkedList's corresponding index
musicList.remove(selectedRow);
System.out.println("Existing rows = "+recordsTable.getRowCount());
// If there are no more rows, disallow user from trying to delete rows
if(selectedRow <= 0)
deleteRecordR_MI.setEnabled(false);
} // deleteRecord()
// Method to query if all cells have changed their states (empty or not)
public boolean queryState()
// Obtaining number of rows
int rows = recordDetails.getRowCount();
int columns = recordDetails.getColumnCount();
boolean isEmpty = false; // cell
System.out.println("Rows = "+rows);
System.out.println("Columns = "+columns);
try{
// Assessing all cells for complete entries
// This approach is flexible, rather than hardcoding the rows available,
// making it more reusable (assuming it will always be 5 columns)
for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
isEmpty = true;
catch(Exception e)
System.out.println(e.getMessage());
return isEmpty;
Now here is the code for the MusicDatabase class
package Practice;
class MusicDatabase
private String songTitle, identity, musicCompany;
private int rank;
private float priceF;
// Defining the constructor
public MusicDatabase(String title, String name, String company, int rankingInt, float price)
songTitle = title;
identity = name;
musicCompany = company;
rank = rankingInt;
priceF = price;
} // constructor
// Other methods
} // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
Thanks!
Reformer...
PS I do hope the code pasted was not too much. Kind regards.... -
Struts2 - ScopedModelDriven - Unable to update the model in session
Hi,
I have a problem implementing ScopedModelDriven.
I Have Model / User Java Bean object in action class.
I am trying to implement concept of same model object being used for 3 JSP pages with PREVIOUS and NEXT button navigation.Data to be updated in Model object for every page navigation and to be saved in session.
It is found the latest data is found from value stack when jsp page is navigated to next page, but not updated in Model object either in request or session scope I am sure I have configured necessary interceptors properly.
This could be easily done in struts1 by setting the Actionform in session scope.Any advice or thought?.
Struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="myPackage" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="myMultipleForm"
class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor">
<param name="scope">session</param>
<param name="name">user</param>
<param name="className">com.ut.p.s2.beans.User</param>
</interceptor>
</interceptors>
<global-results>
<result name="error">/jsp/Error.jsp</result>
<result name="invalid.token">/jsp/Error.jsp</result>
<result name="login">/jsp/login.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping
result="error"
exception="java.lang.Throwable"/>
</global-exception-mappings>
<action name="ShowScopedModel" class="com.ut.p.s2.actions.ServletTestAction" >
<interceptor-ref name="servletConfig"/
<interceptor-ref name="app_common"/>
<result name="model_test_page">/jsp/smodelTest.jsp</result>
<result>/jsp/smodelTest.jsp</result>
</action>
<action name="scopedModelAction_*" class="com.ut.p.s2.actions.ScopedModelDrivenAction" method="{1}">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="prepare"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="scopedModelDriven">
<param name="scope">session</param>
<param name="name">user</param>
<param name="className">com.ut.p.s2.beans.User</param>
</interceptor-ref>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="workflow"/>
<result name="input">/jsp/smodelTest.jsp</result>
<result>/jsp/smodelResult.jsp</result>
<result name="model_test_page">/jsp/smodelTest.jsp</result>
<result name="model_test_page2">/jsp/smodelTest2.jsp</result>
<result name="model_test_page3">/jsp/smodelTest3.jsp</result>
<result name="model_result_page">/jsp/smodelResult.jsp</result>
</action>
</package>
</struts>
Action:
package com.ut.p.s2.actions;
import java.util.ArrayList;
import com.ut.p.s2.beans.Books;
import com.ut.p.s2.beans.Dept;
import com.ut.p.s2.beans.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.interceptor.ScopedModelDriven;
public class ScopedModelDrivenAction extends ActionSupport implements ScopedModelDriven,Preparable {
private User user =null;
private static final long serialVersionUID = 1271130427666936592L;
private String scope = null;
public void prepare() throws Exception {
user = new User();
ArrayList arlList=new ArrayList();
Books b1 = new Books("Java",100);
Books b2 = new Books("VB",200);
arlList.add(b1);
arlList.add(b2);
Dept dept = new Dept();
dept.setDeptNo("100");
dept.setDeptName("Mechanical");
user.setDept(dept);
user.setArlList(arlList);
public String getScopeKey() {
return scope;
public void setModel(Object arg0) {
this.user = (User) arg0;
public void setScopeKey(String arg0) {
scope = arg0;
public Object getModel() {
return user;
public User getUser() {
return user;
public void setUser(User user) {
this.user = user;
public String execute() {
System.out.println("execute()........."+user);
return INPUT;
public String input() throws Exception {
System.out.println("input()........."+user);
return SUCCESS;
public String save() {
System.out.println("save()........."+user);
return "model_result_page";
public String page1() {
System.out.println("page1()........."+user);
System.out.println("page1()....scope....."+scope);
return "model_test_page";
public String page2() {
System.out.println("page2()........."+user);
System.out.println("page2()....scope....."+scope);
return "model_test_page2";
public String page3() {
System.out.println("page3()........."+user);
System.out.println("page3()....scope....."+scope);
return "model_test_page3";
}//end class
JSP Page:
<%@ page errorPage="/jsp/Error.jsp" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<s:head theme="simple"/>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Details</title>
</head>
<body>
<h2>User Details</h2>
<hr>
User Name :<s:property value="name" /><br>
Age :<s:property value="age" /><br>
Hobbies :<s:property value="hobby" /><br>
Country :<s:property value="country" /><br>
<TABLE border="1">
<s:iterator value="arlList" status="row">
<TR>
<TD><s:textfield name="arlList[%{#row.index}].name" value="%{name}" /></TD>
<TD> <s:text name="arlList[%{#row.index}].price" /></TD>
</TR>
</s:iterator>
</TABLE>
<h2>
User Department :<s:property value="dept" /><br>
<s:property value="dept.id" />
<s:property value="dept.name" />
<jsp:include page="Footer.jsp"/>
</body>
</html>I am very surprised that you aren't aware of the CODE tags after being registered here for 5 years. Now your whole post with raw and unformatted code is hard to read. Make use of CODE tags to post code. You can use the CODE button in the toolbar of the message editor to get them.
With regard to your actual problem: as this is a Struts specific issue and you're here at a JSP forum, all I can do is to suggest you to use a forum/mailinglist devoted to Struts if you don't get sufficient support here after a while. -
UPDATE QUERY can't update table
Hi,
During 1500-2000 concurrent users, DB Transaction locks occur. So that Update query can't update table and we get inconsistent data. How can we avoid this inconsistent data?? Why we get transaction locks??
Eg. In update query it update the status of user with completed; but because of transaction lock update query can't update status of user it remains uncompleted. So we can get wrong status of user(inconsistent data). Why UPDATE query update the status
of user???
update table set status='completed', date=@p2,score=@p3 where id=@p1You are not getting inconsistent data, you are getting the data according to the isolation level you are running under. The isolation level determines the locking model and therefore determines any bad dependencies you may experience. Reducing the bad dependencies
through higher isolation level will lower concurrency. *This* is the core concept of Transactional Processing theory.
Furthermore there is not really such a thing as a DB Transaction lock - at least not in the way you mean. SQL server does use DB locks (such as Shared transaction workspace and Exclusive transaction workspace) but the highest level of lock escalation is
the object level (heap or btree) so those are the things you are really interested in. In the ideal would you want all Exclusive, Shared and U locks to be taken at the RID (heaps) or Key (cluster tables) level - and only have few of them per query.
In conclusion think carefully about your query and how it is implimented under the covers by the database engine.
Regards,
Mark Broadbent.
Microsoft Certified Master
Contact me through twitter |
blog | sqlcloud
Please click "Propose as answer" if a post solves your problem
or/and vote the post up if it's been helpful. -
Table Model:: Null Pointer Exception
I have made an application wherein I am using a JTree to display some hierarchy.
Now while scrolling the tree,I display the details in the table.
Data for both the components come from the database.If I continously scroll up and down for some time
in the Tree I get an error in the Table Model
rsmd=rs.getMetaData();
for the above line.It throws NullPointerException,it only happens after scrolling for some time and
not for any particular value.
I update the table model using jtable.setModel().
Plz help.What is actually throwing the NullPointerException? rs.getMetaData() or table.setModel()?
-
Custom Table Model from Default Table Model
I'm creating a customised table model to create a table with column header and empty rows.But it is throwing Component paint_imediatly error.If i pass in empty string to the row vector then setNumRows then no problem. If i do like this later it throws me error in my addNewRow method which was working fine before.Can anyone help?I would realy apreaciate it.Thank you.
KavithaThis must be your lucky day :)
Here is my version of an EditableTableModel which displays an emptyline as the last line
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;
* Custom TableModel, allows addition and removal of records/rows and editting of existing values.
* it also keeps track over which rows have been altered.
* column 0 is a boolean indicating wheter or not to keep this row/record
* @author Maurice Marrink
* @version 1.0
public class EditableTableModel extends AbstractTableModel implements Serializable, TableModelListener
protected ArrayList keep,changed; //houden bij of een rij gedel moet worden en of ie is veranderd (false = delete)
protected ArrayList[] DATA;
protected int emptyLineIndex;
protected String[] kolomNamen;
protected Object[] kolomTypen; // bevat een object van dezelfde class als die kolom
protected int newRowsIndex; // houd bij vanaf welke rij niewe regels zijn toegevoegd ivm het opslaan in de db
protected int[]primecolumns; //houd bij welke kolommen ingevuld moeten worden voordat de volgende regel getoond wordt (default= kolom 1)
public EditableTableModel()
keep = new ArrayList(); //visible
changed=new ArrayList(); // not visisble
primecolumns=new int[0];
DATA=new ArrayList[0];
kolomNamen =new String[0];
kolomTypen=new Object[0];
emptyLineIndex=-1;
newRowsIndex=-1;
* the constructor, creates a new EditableTableModel
*@param data an array of ArrayLists each arrayList contains the values of an entire column
*@param names an array containg the names of the columns
*@param type an array containing Objects which correspond to the objects in the columns
public EditableTableModel(ArrayList[] data, String[] names, Object[] type)
keep = new ArrayList(); //visible
changed=new ArrayList(); // not visisble
primecolumns=new int[1];
primecolumns[0]=1;
DATA=data;
for(int i=0;i<getRowCount();i++)
keep.add(new Boolean(true));
changed.add(new Boolean(false));
kolomNamen=names;
kolomTypen=type;
emptyLineIndex=getRowCount()-1;
addNewLine();
newRowsIndex=emptyLineIndex; // nieuwe regels beginnen op de lege regel
addTableModelListener(this);
* @return the number of rows/records
public int getRowCount()
return DATA[0].size();
*@return the number of columns
public int getColumnCount()
return DATA.length+1;
* returns the object containing the value for this cell
* indexes start at 0 (wheter or not to keep this row), but the actual data starts at 1
*@param row the row in which the cell resides
*@param column the column in which the cell resides
*@return the value of the cell wrapped in the appropiate Object
public Object getValueAt(int row, int column)
if(column==0)
return keep.get(row);
else
return DATA[column-1].get(row);
* allows editing of an existing value
*@param value the new value, should be of the same Object Type as the existing one
*@param row the row nr of the cell
*@param col the column nr of the cell
public void setValueAt(Object value, int row, int col)
if(col==0)
keep.set(row,value);
else
DATA[col-1].set(row,value);
changed.set(row, new Boolean(true));
fireTableCellUpdated(row, col);
* adds a new "empty" row after all the PrimeColums of the last row have been filled with an acceptable value
*@see setPrimeColumns
protected void addNewLine()
try
for(int i=0;i<DATA.length;i++)
if(kolomTypen[i] instanceof Integer)
DATA.add(new Integer(-1));
else
if(kolomTypen[i] instanceof Boolean)
DATA[i].add(new Boolean(false));
else
if(kolomTypen[i] instanceof Long)
DATA[i].add(new Long(-1)); //displayed as "" by cellrenderer
else
DATA[i].add(kolomTypen[i].getClass().newInstance()); //nieuw object aanmaken van het type dat gespecificeerd is, Integers en Booleans moet een waarde meegegeven worden
keep.add(new Boolean(true));
changed.add(new Boolean(false));
emptyLineIndex++;
catch(Exception e)
e.printStackTrace();
public void tableChanged(TableModelEvent e)
if(e.getFirstRow()==emptyLineIndex)//alleen als de emptyLine ge?dit wordt een regel toevoegen
boolean primesfilled=true;
for(int i=0;i<primecolumns.length;i++)
if(getValueAt(emptyLineIndex,primecolumns[i]).equals(null) || getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("")|| getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("-1"))
primesfilled=false;
break;
if(primesfilled) //alleen als de primaire sleutel kolommen ingevuld zijn
addNewLine();
* returns the Class type of the Objects representing the column type
*@param c the column nr
public Class getColumnClass(int c)
if(c==0)
return new Boolean(true).getClass();
else
return kolomTypen[c-1].getClass();
*@param rowIndex the index of the row
*@param columnIndex the index of the column
*@return true if a cell is Editable,false otherwise (all cells are Editable)
public boolean isCellEditable(int rowIndex, int columnIndex)
return true;
* returns the name of the column
*@param column the column index
*@return a String containing the name of the column
public String getColumnName(int column)
if(column==0)
return "";
else
return kolomNamen[column-1];
*@return wheter or not 1 or rows is marked for deletion
public boolean deletionNeeded()
Boolean B;
for(int i=0;i<emptyLineIndex;i++)
B=(Boolean)keep.get(i);
if(!B.booleanValue())
return true;
return false;
* Deletes all rows which are marked for deletion
*@return the number of rows that have been deleted
public int deleteMarkedRows() // zou niets uit moeten maken of je eerst deleteMarkedRows() of isSavedToDB(true) aanroept
int aantalRows=0;
Boolean B;
for(int i=0;i<emptyLineIndex;i++)
B=(Boolean)keep.get(i);
if(!B.booleanValue())
if(deleteRow(i))
aantalRows++;
i--;
return aantalRows;
* deletes a single row
*@param row the row index
*@return true if the row was deleted, false otherwise
protected boolean deleteRow(int row)
boolean result=false;
if(row==emptyLineIndex) // emptyline kan niet gedelete worden
return result;
try
for(int j=0;j<DATA.length;j++)
DATA[j].remove(row);
changed.remove(row);
keep.remove(row);
emptyLineIndex--;
if(row < newRowsIndex)
newRowsIndex--;
result=true;
catch(Exception e)
e.printStackTrace();
return result;
* returns if the row has changed or not
*@param row the row index
*@return true if 1 or more cells in this row had their value changed or if 1 or more rows were added, false otherwise
public boolean hasChanged(int row)
Boolean B=(Boolean)changed.get(row);
return B.booleanValue();
* Methode waarmee men kan bepalen of 1 van de originele waarden ook veranderd is.
* Het geeft dus niet aan of er ook nieuwe rijen zijn toegevoegd.
public boolean hasChanged()
Boolean B;
for(int i=0;i<newRowsIndex;i++)
B=(Boolean)changed.get(i);
if(B.booleanValue())
return true;
return false;
* if true it sets all flags indicating a change to false, else nothing
*@param saved boolean indicating all changes are now to be considerd to be the original values, or not
public void isSavedToDB(boolean saved)
if(saved)
for(int i=0; i<changed.size();i++)
changed.set(i,new Boolean(false));
newRowsIndex=emptyLineIndex;
* @return the row nr. at which newly added entrys begin, updated after isSavedToDB(true) is called
public int getNewRowsIndex()
return newRowsIndex;
* allows the specification of certain columns that need to be filled in, if not a new row will not be made vissible
*@param columns an array containing the column indexes which must be set to a valid value
public void setPrimeColumns(int[] columns)
primecolumns=columns;
* allows retrieval of the PrimeColumns
*@return an arrayof int containing the column indexes
public int[] getPrimeColumns()
return primecolumns;
Ok some of the comments are in dutch go ahead an blame me :(
if you have any questions, just ask.
i also have a TableModel which can use automatic numbering
Oh numbers (currently only Integer and Long) are initiated wth a value of -1 if you want to display them as blank cells like i wanted to you modify a cellrenderer (or use mine)
Mr Mean -
JTable Problem(Default Table Model)
Hi all,
iam using Default Table model for my jtable i want to do pageup and pagedown operation .
TableColumnModel cm1 = new DefaultTableColumnModel();
DefaultTablemodel md = new DefaultTableModel(row,col);
JTable t = new JTable(md,cm1);
i have 500 rows currently in my database i want to display 100 in the first page and if i press the pagedown button the next 100 has to be diplayed wether this is possible here.. if possible please help mee.sample code :
// PagingModel.java
// A larger table model that performs "paging" of its data. This model reports a
// small number of rows (e.g., 100 or so) as a "page" of data. You can switch pages
// to view all of the rows as needed using the pageDown( ) and pageUp( ) methods.
// Presumably, access to the other pages of data is dictated by other GUI elements
// such as up/down buttons, or maybe a text field that allows you to enter the page
// number you want to display.
import javax.swing.table.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class PagingModel extends AbstractTableModel {
protected int pageSize;
protected int pageOffset;
protected Record[] data;
public PagingModel( ) {
this(10000, 100);
public PagingModel(int numRows, int size) {
data = new Record[numRows];
pageSize = size;
// Fill our table with random data (from the Record( ) constructor).
for (int i=0; i < data.length; i++) {
data[i] = new Record( );
// Return values appropriate for the visible table part.
public int getRowCount( ) { return Math.min(pageSize, data.length); }
public int getColumnCount( ) { return Record.getColumnCount( ); }
// Work only on the visible part of the table.
public Object getValueAt(int row, int col) {
int realRow = row + (pageOffset * pageSize);
return data[realRow].getValueAt(col);
public String getColumnName(int col) {
return Record.getColumnName(col);
// Use this method to figure out which page you are on.
public int getPageOffset( ) { return pageOffset; }
public int getPageCount( ) {
return (int)Math.ceil((double)data.length / pageSize);
// Use this method if you want to know how big the real table is. You could also
// write "getRealValueAt( )" if needed.
public int getRealRowCount( ) {
return data.length;
public int getPageSize( ) { return pageSize; }
public void setPageSize(int s) {
if (s == pageSize) { return; }
int oldPageSize = pageSize;
pageSize = s;
pageOffset=(oldPageSize * pageOffset) / pageSize;
fireTableDataChanged( );
// Update the page offset and fire a data changed event (all rows).
public void pageDown( ) {
if (pageOffset < getPageCount( ) - 1) {
pageOffset++;
fireTableDataChanged( );
// Update the page offset and fire a data changed (all rows).
public void pageUp( ) {
if (pageOffset > 0) {
pageOffset--;
fireTableDataChanged( );
// We provide our own version of a scrollpane that includes
// the Page Up and Page Down buttons by default.
public static JScrollPane createPagingScrollPaneForTable(JTable jt) {
JScrollPane jsp = new JScrollPane(jt);
TableModel tmodel = jt.getModel( );
// Don't choke if this is called on a regular table . . .
if (! (tmodel instanceof PagingModel)) {
return jsp;
// Go ahead and build the real scrollpane.
final PagingModel model = (PagingModel)tmodel;
final JButton upButton = new JButton("Up");
upButton.setEnabled(false); // Starts off at 0, so can't go up
final JButton downButton = new JButton("Down");
if (model.getPageCount( ) <= 1) {
downButton.setEnabled(false); // One page...can't scroll down
upButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
model.pageUp( );
// If we hit the top of the data, disable the Page Up button.
if (model.getPageOffset( ) == 0) {
upButton.setEnabled(false);
downButton.setEnabled(true);
downButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
model.pageDown( );
// If we hit the bottom of the data, disable the Page Down button.
if (model.getPageOffset( ) == (model.getPageCount( ) - 1)) {
downButton.setEnabled(false);
upButton.setEnabled(true);
// Turn on the scrollbars; otherwise, we won't get our corners.
jsp.setVerticalScrollBarPolicy
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy
(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add in the corners (page up/down).
jsp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, upButton);
jsp.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, downButton);
return jsp;
// Record.java
// A simple data structure for use with the PagingModel demo
class Record {
static String[] headers = { "Record Number", "Batch Number", "Reserved" };
static int counter;
String[] data;
public Record( ) {
data = new String[] { "" + (counter++), "" + System.currentTimeMillis( ),
"Reserved" };
public String getValueAt(int i) { return data[i]; }
public static String getColumnName(int i) { return headers[i]; }
public static int getColumnCount( ) { return headers.length; }
class PagingTester extends JFrame {
public PagingTester( ) {
super("Paged JTable Test");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
PagingModel pm = new PagingModel( );
JTable jt = new JTable(pm);
// Use our own custom scrollpane.
JScrollPane jsp = PagingModel.createPagingScrollPaneForTable(jt);
getContentPane( ).add(jsp, BorderLayout.CENTER);
public static void main(String args[]) {
PagingTester pt = new PagingTester( );
pt.setVisible(true);
} -
Table Model Listener conflict?
Before I post my problem, please let me admit that I am a fairly new beginner to Java with a problem too big for my knowledge. So please bear with my ignorance.
I have created a table with a table model that changes size at the action of a button (will create as many rows as a certain user-entered value). This seems to be working fine.
The table I am creating contains some default values, but the user will need to be able to modify these values. To read these values, I need a Table Model Listener.
However, when I add the Table Model Listener, the above feature (change the size of the table at the action of the button) stops working. Is the table listener incompatible with a dynamic-sized table? Is there a step a should add in between to let the table listener know that the table data is final and read it? Am I doing things in the wrong order?
I would appreciate any suggestions, as I am quite clueless.
Thanks
maccanenaNo that shouldn't matter, the listener is doing something you don't want, the code posted works for me.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class TableTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
showUI();
protected static void showUI() {
Object [][] ptable = {{"p1", 2.0}};
String[] colnamesp = { "p name:", "p value:" };
final DefaultTableModel pTableModel = new DefaultTableModel(ptable,colnamesp);
JTable jTable1 = new JTable(pTableModel);
final JTextField nvarsEntry = new JTextField("1");
JButton updateButton = new JButton("Update table");
updateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent updateevt) {
try{
int nvars = Integer.parseInt(nvarsEntry.getText());
int j;
int length = pTableModel.getRowCount();
if (length<nvars) {
for (j=length;j<nvars;j++) {
pTableModel.addRow(new Object[] {"p"+String.valueOf(j+1), 2.0});
else if (length>nvars) {
for (j=nvars;j<(length+1);j++) {
pTableModel.removeRow(nvars);
} catch (Exception e) {
jTable1.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent evtable1) {
int row = evtable1.getFirstRow();
int column = evtable1.getColumn();
// Do something with the data...
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.add(updateButton, BorderLayout.PAGE_START);
contentPane.add(nvarsEntry, BorderLayout.PAGE_END);
contentPane.add(new JScrollPane(jTable1), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
} -
HtmlDataTable (seem to be) not updating HtmlSelectOneListBox model values
I have a table with multiple rows of model objects in a list. One of the controls in the row is a selectone list box with its own list of selectItem objects
On submit and back, any text controls I have in the table and also in the form are retaining their state and updating the model values
But the selctone list box is not updating the models?
If I follow the phase events I see the update model phase passing through. Not sure why the data in the ui is not submitted to the model
If I locate the ui control and ask its selected value I see the changed value. But this is not communicated to the the model.
Is there a known issue with a data table and select drop downs, especially for keeping the state.
The backing bean is session scope where the data for the table is maintained as a list of pojo objects. The drop down values are kept in a list of SelectItem objects
Thanks in advance for help
SatyaIn short, my fault.
I have the list items bound to a list. But the I haven't bound the HtmlSelectOneList box with a value binding. I was under the impression that the selected item from this list is kept with the item as in the case of html. But in this case it is kept with the parent via its value attribute.
Now the state is kept as the form goes back and forth. -
Hi,
I have a requirement for my application. I need to display a timer inside the cell of JTable. The table will be displaying records of multiple users visiting the site. The column should display the total time spent on the page. I am using a customized Table Model. How can I go about it?
Thanks,
AjitHi,
See the following coding.
In short,
< b &rt tableModel.fireTableCellUpdated(row,column); < /b &rt
raises the event. So that JTable will listen that event, and updates
that particular cell only.
You can create a thread, that keeps track of website visiting
log of all persons. If the time change, you can invoke that method.
import javax.swing.*;
import javax.swing.border.DefaultTableModel;
public class MyModel extends DefaultTableModel
Object [] items;
public MyModel(Object [] items) {
this.items=items;
public int getColumnCount() {
return 2;
public int getRowCount() {
return 4;
public Object getValueAt(int row,int column) {
// The first column is fixed Item 1, Item 2, Item 3 etc.
if(column==0)
return "Person "+(row+1);
// The second column varies with "items".
else
return items[row]+" seconds";
public static void main(String []args) {
JFrame f=new JFrame("Testing single cell editor");
final Object items[]=new Object[]{"1","2","3","4"};
final MyModel model=new MyModel(items);
// A table with 2 rows and 2 columns
JTable table=new JTable(model);//new OurTableModel());
// Set our editor as table's editor
//table.setDefaultEditor(Object.class,new SingleCellEditor());
// Add to a scroll pane
JScrollPane pane=new JScrollPane(table);
pane.setBounds(50,50,200,200);
f.getContentPane().setLayout(null);
f.getContentPane().add(pane);
// Close on exit
f.setDefaultCloseOperation(3);
// Show the frame
f.show();
Thread t=new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(1000);
items[2]=""+(Integer.parseInt(""+items[2])+1);
model.fireTableCellUpdated(2,1);
catch (InterruptedException ignored) {
t.start();
See that there my be compilation errors. But the logic is same. The same
I applied and got it.
Bye.. Bye.. -
Can I modify a table model outside of the event thread if it's not seen?
I have a JTable that I use to display several table models (I'm extending DefaultTableModel); I switch between the models using JTable.setModel.
If model A is active and currently being viewed, I of course make sure any updates are done using SwingUtilities.invokeLater().
My question is: Can I modify an "inactive" table, say table B, without using invokeLater(), for example B.setValueAt() etc.Isn't a model connected to an instance by JTable.setModel()? (Or by passing the model as a parameter in new JTable()) Yea. I meant connected to a JTable's UI. Or more specifically, listeners are installed on the model.
if data is changing and the user is not currently viewing that data, I want to change the table model in another threadI would argue that this is thread safe:
1) When a table becomes 'inactive' (not showing in any way) then you set the model to some static empty one.
table.setModel(EMPTY_MODEL);This should happen on the EventDispatchThread. Setting the model to the empty one will uninstall all the listeners on the actual model.
2) Freely modify the table's actual model in another Thread.
3) When the table is about to become 'active', then you set the model back to the original one.
table.setModel(originalModel);This should happen on the EventDispatchThread. In particular, the other thread should execute it with an invoke later. That way, proper synchronization occurs and the EDT sees all the changes made to the original model. -
Difference between table and table model
From what I've understood till now, in a JTable, the table itself is actually only a "display area" while the actual data is located in the table model. Is this correct?
Does this mean it is possible to delete rows and columns within the table itself without affecting the actual data in the table model?Hi,
ok, I will try to answer your second question "is it possible to delete rows and columns in the table but not in the table model"?
The table - lets say the table's view - reflects the data of the data model only, if you fire the correct notification messages via the TableModelListener interface - JTable itself is a TableModelListener and updates its display accordingly to these messages - it never holds data by itself - if something is to be redrawn in the view, JTable ask the model via getValueAt(...) for the data and renders it using one of the cellrenderers delivered by the column of the column model resp. one of the registered default renderers.
Now to your question - you can't delete a row in the tables view, without any change in the table model, as so the data isn't hold by the table's view, it is only held by the table model. But the other way round, it is possible - often accidentially - you can change the data in the table model and forget to fire a notification message for it via the TableModelListener interface - in this case, JTable will not update its view - and the table may look strange, if parts of its view is hidden by other applications and afterwards redrawn, when this application closes. Only the parts, that were hidden, will be redrawn - and this is done with the new data. So, keep track of always sending the correct notification message with every change you make in the table model, so that JTable is able to keep its view up to date.
Hope this helps
greetings Marsian -
"Error in updating Table J_1iexchdr"
Hi ,
When I am creating the excise invoice, It's terminated the program and gives the following error
"Error in updating Table J_1iexchdr"
What can be the reason?
Regards
PremHi prem
Look if these threads can help
RG23C Update Problem
Problem in SAP Script
billing document not creating
return delivery
************Reward points if usefull**************
Maybe you are looking for
-
Error when installing Premier 9 to Mac
I am attempting to install my Adobe Premier Elements 9 from my disc (not purchased from Adobe, but from Amazon). The computer recognizes the disc and when it begins installation it spits the disc out and shows this error message. Exit Code: 7 ------
-
Generating document in XML in RM
Hi, I have a function module where I create a document in XML and store it in RM. In the code of this funcion module, I first create the empty document using the FM SRM_DOCUMENT_CREATE, and then I add the content to this document with the FM SRM_DOCU
-
HTML Map tag zoom problem.
Hi, We have discovered a problem with our webpage that only occurs on safari. We have an image with an image where we use an <map><area> tags to indicate click-able hot spots on the image. When you change the zoom level in the browser, increasing or
-
hi, I have created an outgoing excise invioce usinh j1iin.I has created an excise invoice with same no.but different internal number. but when i am cancelling excise with same excise with excise invoice no it is showing the earliear one and cancelled
-
I am trying to update RPM's using up2date from server(OS version OEL5.4), when i am trying update RPM's, its not allowing me to update RPM's any ideas..? up2date --force oracleasm* Fetching Obsoletes list for channel: ol5_x86_64_latest... Name Versio