Updating data in jtable...
hi everyone,
I have some problem updating data in the jtable, first I get data from database and fill the table in with it...then the table just get disabled...
i have a table called jTable, and a DefaultTableModel wich I applied the jTable with....hope any body could helps...
Thanx
Code:
public class fillDbGui extends JFrame
Vector colNames = new Vector();
Vector data = new Vector();
private DefaultTableModel model = new DefaultTableModel();
private JTable jTable = new JTable(model);
public JScrollPane jspVertical;
public void db2vector()
destroyTable();
//add database data to vectors
try
ResultSet select = conc.executeQuery("SELECT * FROM college ORDER BY id");
ResultSetMetaData md = select.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
colNames.addElement( md.getColumnName(i) );
while (select.next())
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
row.addElement( select.getObject(i) );
data.addElement(row);
select.close();
catch(Exception exc)
System.out.println(exc.getMessage());
System.out.println(exc.getStackTrace());
model.setDataVector(data,colNames);
jspVertical = new JScrollPane(jTable);
getContentPane().add(jspVertical);
public void destroyTable()
data.removeAllElements();
colNames.removeAllElements();
jspVertical=null;
}
... I only added this constructor to be able to run your code:
public fillDbGui(){
setTitle("Fill DB GUI");
setSize(600,500);
setLocationRelativeTo(null);
try{
DriverManager.registerDriver( new com.mysql.jdbc.Driver() );
DriverManager.registerDriver( new sun.jdbc.odbc.JdbcOdbcDriver() );
connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USER, USER_PASSWORD);
conc = connection.createStatement();
System.out.println("Successfully connected to database '" +DATABASE_NAME+ "'\n");
}catch(SQLException ex){
System.out.println("Connection failed\n");
JOptionPane.showMessageDialog( this, ex.getMessage(),
"Fill_DB_GUI: SQLException", JOptionPane.ERROR_MESSAGE);
db2vector();
public static void main(String args[]) {
new fillDbGui().setVisible(true);
private final String DATABASE_NAME = "test";
private final String DATABASE_URL = "jdbc:mysql://localhost:3306/" + DATABASE_NAME;
// private final String DATABASE_URL = "jdbc:odbc:" + DATABASE_NAME;
private final String TABLE_NAME = "testuhrand";
private final String DATABASE_USER = "root";
private final String USER_PASSWORD = "sql";
private Statement conc;
private Connection connection;
Similar Messages
-
Hi all,
once I have created a JTable as follows:
final String[] columnNames = {"",""};
final Object[][] data = {
{"a", "b"},
{"c", "d"},
{"e", "f"}
JTable myTable = new JTable(data, columnNames);
What's the most easy way to add or remove values into myTable?
Do I have to update the data array or is there methods like myTable.addValue() or myTable.updateData(Object[][])?
And after the update of the values, do I have to do something to refresh the GUI displaying myTable?
Thanks for your help.Hello Camickr,
I create my table model and read data from a text file. Then I create a table with this model. But when I press button, no table show. Could you please tell me why? Thanks! The code show as follow:
(1) table model
import javax.swing.*;
import javax.swing.table.*;
import java.io.*;
import java.beans.*;
import java.util.*;
class ADataModel extends AbstractTableModel implements java.io.Serializable{
// Imagine the data coming from JDBC
// With column names from ResultSetMetaData
String[] columnNames={};
Vector rows = new Vector();
public void fillvalue(String curFileDir,String curFile)
try
char[] buff = new char[256];
int line,column,index,strLength;
String str;
String tempStr;
line=1;
File f=new File(curFileDir, curFile);
if(!f.exists())
{ //file not there, abort
return;
BufferedReader in=new BufferedReader (new FileReader(f));
//read file
while ((str = in.readLine())!= null)
str=str+" ";
buff=str.toCharArray();
tempStr="";
strLength=str.length();
column=0;
index=1;
if(line==1)
columnNames=new String[21];
// Vector fieldName = new Vector();
while (index < strLength)
if(buff[index]!=' ')
tempStr=tempStr+buff[index];
else if(buff[index-1]!=' ')
columnNames[column]=tempStr;
//fieldName.addElement(tempStr);
tempStr="";
System.out.println(columnNames[column]);
column++;
index++;
/* int columnSize= fieldName.size();
columnNames=new String[columnSize+1];
fieldName.copyInto(columnNames);
System.out.println(fieldName);
else
Vector newRow = new Vector();
tempStr="";
while (index < strLength)
if(buff[index]!=' ')
tempStr=tempStr+buff[index];
else if(buff[index-1]!=' ')
newRow.addElement(tempStr);
tempStr="";
column++;
index++;
rows.addElement(newRow);
line++;
in.close();
System.out.println(rows);
catch(Exception e)
e.printStackTrace();
// Save array lengths for performance reasons
private int numColumns = columnNames.length;
private int numRows = rows.size();
public int getColumnCount() {
return numColumns;
public int getRowCount() {
return numRows;
public Object getValueAt (int row, int column)
try
return ((Vector)rows.elementAt(row)).elementAt(column);
catch(Exception e)
e.printStackTrace();
return null;
public String getColumnName (int columnIndex)
return columnNames[columnIndex];
(2)void button2_ActionPerformed(java.awt.event.ActionEvent event)
// to do: code goes here.
String curFileDir="";
String curFile="";
try
FileDialog fd = new FileDialog(this);
fd.setMode(FileDialog.LOAD);
fd.setVisible(true);
curFileDir = fd.getDirectory();
curFile = fd.getFile();
if((JTextField1.getText()==null)||(!(curFileDir==null)))
JTextField1.setText(curFileDir);
if ( (curFile == null) || (curFile.equals("")))
//no selected file so abort
return;
catch(Exception e)
e.printStackTrace();
// to do: code goes here.
ADataModel myModel = new ADataModel();
myModel.fillvalue(curFileDir,curFile);
JTable1.setModel(myModel);
//myModel.notifyAll();
JTable1.setVisible(true);
} -
How can i update data in JTable at run time ?
i am trying to build a client/server architecture for conducting quizzes & online tests.. My client will return a object to the server after the test is over, which contains details about the participant, his score and other details. i am putting the incoming object to an Vector. I'll create a new thread each time for the incoming connection and insert the object to the Vector.. Now, please tell me tat, how can i update my table automatically at run time so tat, my table is updated whenever a new object is entered into vector..
here is my code for the table..
public class MyTableModel extends AbstractTableModel {
String columNames[] = { "ID", "NAME", "COLLEGE", "SCORE", "CELL" };
/** Creates a new instance of MyTableModel */
public MyTableModel() {
Main.List = new Vector();
SetDefaultData();
public int getRowCount() {
return Main.List == null ? 0 : Main.List.size();
public int getColumnCount() {
return columNames.length;
public String getColumnName(int column) {
return columNames[column];
public boolean isCellEditable(int row,int col) {
return false;
public Object getValueAt(int rowindex, int columnindex) {
if(rowindex < 0 || rowindex >= getRowCount())
return "";
Student row = (Student)Main.List.elementAt(rowindex);
switch (columnindex)
case 0 : return row.id;
case 1 : return row.name;
case 2 : return row.college;
case 3 : return row.score;
case 4 : return row.cell;
return "";
public String getTitle() {
return "Student Table";
private void SetDefaultData() {
Main.List.removeAllElements();
Main.List.addElement(new Student("CS041","Keerthivasan M","MNM",95,"9884326321"));
Main.List.addElement(new Student("CS012","Arun M","MNM",90,"9884825780"));
Main.List.addElement(new Student("CS019","Balaji S","MNM",79,"9841742068"));
Main.List.addElement(new Student("CS005","Anand R","MNM",89,"9884130727"));
Main.List.addElement(new Student("CS045","Manish J","MNM",55,"9841624625"));
Main.List.addElement(new Student("CS013","Mangal S","MNM",5,"9841961742"));
}In the future Swing related questions should be posted in the Swing forum.
how can i update my table automatically at run time so tat, my table is
updated whenever a new object is entered into vector..You don't update the Vector directly. You should be creating a method in your TableModel, called "addRow(...)". This method will do two things:
a) add the Student object to the Vector
b) invoke the fireTableRowsInserted(..) method of AbstractTableModel. This will cause the table to be repainted. -
Query regarding updating rows in JTable
Query regarding updating rows in JTable
Hello,
I have a JTable with 6 columns and 1000s of rows (which are data read from flat files)
I can select 1 or more rows and change the values of the
columns. each time I do this I need to update the values
in the flat file.
Currently I assign the updated Jtable values to a vector
Vector rowVector = (Vector)defaultModel.getDataVector();
then I iterate over the vector and compare the values with the (old) data
in the JTable.
for(int rowCount = 0; rowCount<rowVector.size(); rowCount++){
Vector v = (Vector)rowVector.elementAt(rowCount);
//smsList is the Vector that contains the old JTable values
for(int i=0; i<smsList.size(); i++){
//If colums values have been changed; add that
//vector value to another vector
selectedsmsList.add(smsList.get(i));
for(int i=0; i<selectedsmsList.size(); i++){
//Update the values in the flat file
}This works fine except that it takes ages to iterate over the updated vecor and un-updated,old vector; is there any way to directly get the list of rows that were updated in the jtable; so that I can directly do an I/O operation to update the jtablke values?Just a suggestion.
You could add a listener and use a vector of booleans to keep track of the rows that have been changed. You could then iterate through this boolean vector and update the changed rows.
See
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#modelchange
Don't know whether this will be helpful.
Regards, Darryl -
I have a problem, The scenario is that when I click any folder that si in my JTable's first row, the table is update by removing all the rows and showing only the contents of my selected folder. Right now it's not removing the rows and instead throwing exceptions. The code is attached. The methods to look are upDateTabel(...) and clearTableData(....), after clearing all my rows then I proceed on adding my data to the Jtable and inserting rows but it's not being done. May be I have a problem in my DefaultTableModel class. Please see the code below what I am doing wrong and how should I do it. Any help is appreciated.
Thanks
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class SimpleTable extends JPanel{
/** Formats the date */
protected SimpleDateFormat formatter;
/** variable to hold the date and time in a raw form for the directory*/
protected long dateDirectory;
/** holds the readable form converted date for the directories*/
protected String dirDate;
/** holds the readable form converted date for the files*/
protected String fileDate;
/** variable to hold the date and time in a raw form for the file*/
protected long dateFile;
/** holds the length of the file in bytes */
protected long totalLen;
/** convert the length to the wrapper class */
protected Long longe;
/** Vector to hold the sub directories */
protected Vector subDir;
/** holds the name of the selected directory */
protected String dirNameHold;
/** converting vector to an Array and store the values in this */
protected File directoryArray[];
/** hashtable to store the key-value pair */
protected static Hashtable hashTable = new Hashtable();
/** refer to the TableModel that is the default*/
protected MyTableModel tableModel;
/** stores the path of the selected file */
protected static String fullPath;
/** stores the currently selected file */
protected static File selectedFilename;
/** stores the extension of the selected file */
protected static String extension;
protected int COLUMN_COUNT = 4;
protected Vector data = new Vector( 0, 1 );
protected final JTable table;
/** holds the names of the columns */
protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
public SimpleTable(File directoryArray[])
this.setLayout(new BorderLayout());
this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
(SimpleTable.hashTable).clear();
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
dateDirectory = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateDirectory));
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
tableModel = new MyTableModel();
table = new JTable( tableModel );
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(false);
table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.addMouseListener(new MouseAdapter()
public void mouseReleased(MouseEvent e)
Object eventTarget = e.getSource();
if( eventTarget == table )
upDateTable(table);
table.tableChanged( new javax.swing.event.TableModelEvent(tableModel) ) ;
DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
this.add(scrollPane, BorderLayout.CENTER);
* Searches the Hashtable and returns the path of the folder or the value.
public File findPath(String value)
return (File)((SimpleTable.hashTable).get(value));
* This clears the previous data in the JTable
public void clearTableData(JTable table)
for(int row = 0; row < table.getRowCount() ; row++)
//for (int col = 0; col < table.getColumnCount() ; col++)
tableModel.deleteSelections( row );
tableModel.fireTableStructureChanged();
tableModel.fireTableRowsDeleted(0,table.getRowCount());
//table.getModel().fireTableChanged(new TableModelEvent(table.getModel()));
private void upDateTable(JTable table)
if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
File argument = findPath(dirNameHold);
if(argument.isFile())
CMRDialog.fileNameTextField.setText(argument.getName());
try
fullPath = argument.getCanonicalPath();
selectedFilename = argument.getCanonicalFile();
CMRDialog.filtersComboBox.removeAllItems();
extension = fullPath.substring(fullPath.lastIndexOf('.'));
CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
catch(IOException e)
System.out.println("THE ERROR IS " + e);
return;
else if(argument.isDirectory())
String path = argument.getName();
//find the system dependent file separator
//String fileSeparator = System.getProperty("file.separator");
CMRDialog.driveComboBox.addItem(" " + path);
subDir = Search.subDirs(argument);
/**TBD:- needs a method to convert the vector to an array and return the array */
directoryArray = new File[subDir.size()];
int indexCount = 0;
/** TBD:- This is inefficient way of converting a vector to an array */
Iterator e = subDir.iterator();
while( e.hasNext() )
directoryArray[indexCount] = (File)e.next();
indexCount++;
/** now calls this method and clears the previous data */
clearTableData(table);
(SimpleTable.hashTable).clear();
//data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
dateDirectory = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateDirectory));
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
// tableModel.fireTableDataChanged();
// tableModel.fireTableRowsInserted(0,1);
table.revalidate();
table.validate();
class MyTableModel extends DefaultTableModel
int totalRows;
int totalCols;
public MyTableModel()
super();
setColumnIdentifiers (columnNames);
this.totalRows = data.size();
this.totalCols = columnNames.length;
// this will return the row count of your table
public int getRowCount()
return totalRows;
// this return the column count of your table
public int getColumnCount()
return totalCols;
// this return the data for each cell in your table
public Object getValueAt(int row, int col)
MyObj obj = (MyObj)data.elementAt( row );
if( obj != null )
if( col == 0 ) return( obj.first );
else if( col == 1 ) return( obj.last );
else if( col == 2 ) return( obj.third );
else if( col == 3 ) return( obj.fourth );
else return( "" );
return "";
// if you want your table to be editable then return true
public boolean isCellEditable(int row, int col)
return false;
// if your table is editable edit the data vector here and
// call table.tableChanged(...)
public void setValueAt(Object value, int row, int col)
protected void deleteSelections (int rows)
try
removeRow(rows);
catch(ArrayIndexOutOfBoundsException e)
System.out.println("The error in the row index " + rows);
fireTableDataChanged() ;
class MyObj
String first;
String last;
String third;
String fourth;
public MyObj( String f, String l, String t, String fo )
this.first = f;
this.last = l;
this.third = t;
this.fourth = fo;
#####################################The following code works fine but it doesn't show me the new updated date in my JTable. I tried to print the values that I am getting and it does give the values on the prompt but doesn't show me on the JTable only first two are shown and the rest of the table is filled with the same values. I don't know what's going on and am tired of this TableModel thing so pla. take a time to give me some suggestions. Thanks
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class SimpleTable extends JPanel {
/** Formats the date */
protected SimpleDateFormat formatter;
/** two-dimensional array to hold the information for each column */
protected Object data[][];
/** variable to hold the date and time in a raw form for the directory*/
protected long dateDirectory;
/** holds the readable form converted date for the directories*/
protected String dirDate;
/** holds the readable form converted date for the files*/
protected String fileDate;
/** variable to hold the date and time in a raw form for the file*/
protected long dateFile;
/** holds the length of the file in bytes */
protected long totalLen;
/** convert the length to the wrapper class */
protected Long longe;
/** Vector to hold the sub directories */
protected Vector subDir;
/** holds the name of the selected directory */
protected String dirNameHold;
/** converting vector to an Array and store the values in this */
protected File directoryArray[];
/** hashtable to store the key-value pair */
protected static Hashtable hashTable = new Hashtable();
/** refer to the TableModel that is the default*/
protected DefaultTableModel model;
/** stores the path of the selected file */
protected static String fullPath;
/** stores the currently selected file */
protected static File selectedFilename;
/** stores the extension of the selected file */
protected static String extension;
protected Vector m = new Vector(0,1);
/** holds the names of the columns */
protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
public SimpleTable(File directoryArray[])
this.setLayout(new BorderLayout());
this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
(SimpleTable.hashTable).clear();
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
data[k][0] = directoryArray[k].getName();
data[k][2] = "File Folder";
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data[k][3] = dirDate;
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
data[k][0] = directoryArray[k].getName();
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data[k][1] = longe + " Bytes";
dateFile = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateFile));
data[k][3] = fileDate;
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
model = new DefaultTableModel();
model.addTableModelListener( new TableModelListener(){
public void tableChanged( javax.swing.event.TableModelEvent e )
System.out.println("************ I am inside the table changed method ********" );
final JTable table = new JTable(model);
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(false);
table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.addMouseListener(new MouseAdapter()
/* public void mousePressed(MouseEvent e)
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
/* if(e.getClickCount() >= 2 &&
(table.getSelectedColumn() == 0) &&
((table.getColumnName(0)).equals(columnNames[0])))
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
upDateTable(table);
public void mouseReleased(MouseEvent e)
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
/* if(e.getClickCount() >= 2 &&
(table.getSelectedColumn() == 0) &&
((table.getColumnName(0)).equals(columnNames[0]))) */
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
upDateTable(table);
/** set the columns */
for(int c = 0; c < columnNames.length; c++)
model.addColumn(columnNames[c]);
/** set the rows */
for(int r = 0; r < data.length; r++)
model.addRow(data[r]);
DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
this.add(scrollPane, BorderLayout.CENTER);
* Returns the number of columns
public int getColumnTotal()
return columnNames.length;
* Returns the number of rows
public int getRowTotal(Object directoryArray[])
return directoryArray.length;
private void upDateTable(JTable table)
if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
File argument = findPath(dirNameHold);
if(argument.isFile())
CMRDialog.fileNameTextField.setText(argument.getName());
try
fullPath = argument.getCanonicalPath();
selectedFilename = argument.getCanonicalFile();
CMRDialog.filtersComboBox.removeAllItems();
extension = fullPath.substring(fullPath.lastIndexOf('.'));
CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
catch(IOException e)
System.out.println("THE ERROR IS " + e);
return;
else if(argument.isDirectory())
String path = argument.getName();
//find the system dependent file separator
//String fileSeparator = System.getProperty("file.separator");
CMRDialog.driveComboBox.addItem(" " + path);
subDir = Search.subDirs(argument);
/**TBD:- needs a method to convert the vector to an array and return the array */
directoryArray = new File[subDir.size()];
int indexCount = 0;
/** TBD:- This is inefficient way of converting a vector to an array */
Iterator e = subDir.iterator();
while( e.hasNext() )
directoryArray[indexCount] = (File)e.next();
indexCount++;
/** now calls this method and clears the previous data */
clearTableData(table);
(SimpleTable.hashTable).clear();
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
m.clear();
data = null;
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
System.out.println("Inside the if part");
data[k][0] = directoryArray[k].getName();
table.setValueAt(directoryArray[k].getName(),k,0);
//model.fireTableCellUpdated(k,0);
data[k][2] = "File Folder";
table.setValueAt("File Folder",k,2);
//model.fireTableCellUpdated(k,2);
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data[k][3] = dirDate;
table.setValueAt(dirDate,k,3);
//model.fireTableCellUpdated(k,3);
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
m.add(data);
model.addRow(m);
model.fireTableDataChanged();
else if(directoryArray[k].isFile())
System.out.println("******* Inside the else part *******");
data[k][0] = directoryArray[k].getName();
System.out.println("The Name is == " + data[k][0]);
table.setValueAt(directoryArray[k].getName(),k,0);
System.out.println("The table cell value of the name is == " + table.getValueAt(k,0));
//model.fireTableCellUpdated(k,0);
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data[k][1] = longe + " Bytes";
System.out.println("The length == " + data[k][1]);
table.setValueAt(longe + " Bytes",k,1);
System.out.println("The table cell value of the length is == " + table.getValueAt(k,1));
//model.fireTableCellUpdated(k,0);
dateFile = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateFile));
data[k][3] = fileDate;
System.out.println("The modified date == " + data[k][3]);
table.setValueAt(fileDate,k,3);
System.out.println("The table cell value of the name is == " + table.getValueAt(k,3));
//model.fireTableCellUpdated(k,0);
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]); }
m.add(data);
model.addRow(m);
model.fireTableDataChanged();
// model.fireTableDataChanged();
// model.fireTableRowsInserted(0,1);
table.revalidate();
table.validate();
else
* Searches the Hashtable and returns the path of the folder or the value.
public File findPath(String value)
return (File)((SimpleTable.hashTable).get(value));
* This clears the previous data in the JTable
public void clearTableData(JTable table)
for(int row = 0; row < table.getRowCount() ; row++)
for (int col = 0; col < table.getColumnCount() ; col++)
table.setValueAt(null, row , col);
model.fireTableStructureChanged();
### -
Hi all,
I am trying to update database from Jtable. I added Jtable to scrollpane .
My question is..
after updating the Jtable..I want to save the details to database..when I click save button on my screen...how to do that? Please help me out! Thanks in advance..
Here is the code that I wrote...
public class VasuTest extends JFrame {
private boolean DEBUG = true;
Vector column_list = new Vector();
Vector rows = new Vector();
public VasuTest() {
super("VasuTest");
JToolBar toolBar = new JToolBar();
JButton button = null;
button = new JButton("Send Email");
button.setToolTipText("This is the Exit button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Send Email");
toolBar.add(button);
button = new JButton("Save");
button.setToolTipText("This is the Save button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Save");
toolBar.add(button);
button = new JButton("Exit");
button.setToolTipText("This is the Exit button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
toolBar.add(button);
JPanel ContentPane = new JPanel();
ImageIcon i1 = new ImageIcon("Dongle.gif");
JLabel j1 = new JLabel( i1, JLabel.CENTER);
ContentPane.add(j1,BorderLayout.CENTER);
setContentPane(ContentPane);
JDBCT myModel = new JDBCT();
String q = "select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no";
myModel.setQuery();
final Font f = new Font("SansSerif", Font.BOLD, 10);
JTable table = new JTable(myModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Container ContentPane = getContentPane();
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize ( new Dimension ( 770, 400 ) );
ContentPane.add(toolBar,BorderLayout.CENTER);
//Add the scroll pane to this window.
ContentPane.add(scrollPane,BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
public class JDBCT extends AbstractTableModel {
Vector cache; // will hold String[] objects...
int colCount;
int rowHeight;
String [] headers;
Connection db;
Connection conn;
Statement statement;
String currentURL;
// public QueryTableModel() {
// cache = new Vector();
// new oracle.jdbc.driver.OracleDriver();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
String url = "jdbc:odbc:c3-erp,s3,s3";
public String getColumnName(int i) {
if (i == 0) { return "Email No" ; } else
if (i == 1) { return "Email Line No.";} else
if (i == 2) { return "Customer";} else
if (i == 3) { return "Customer Name";} else
if (i == 4) { return "Date";} else
if (i == 5) { return "Batch No";} else
if (i == 6) { return "Customer PO";} else
if (i == 7) { return "Upgrade From Part";} else
if (i == 8) { return "Part Description";} else
if (i == 9) { return "Upgrade To Part";} else
if (i == 10) { return "Product Id";} else
if (i == 11) { return "Quantity";} else
if (i == 12) { return "Price";} else
if (i == 13) { return "Encypted Sum ID";} else
if (i == 14) { return "Decrypted Serial No";} else
if (i == 15) { return "Key";} else
if (i == 16) { return "Status";} else
if (i == 17) { return "Approved";} else
if (i == 18) { return "End Customer";} else
if (i == 19) { return "Sales Order";} else
if (i == 20) { return "SO Line";} else
if (i == 21) { return "Sales Order End Customer";} else
if (i == 22) { return "Sales Order End Customer Name";} else
if (i == 23) { return "Shipment";} else
if (i == 24) { return "Shipment Line";} else
if (i == 25) { return "Errors";} else
if (i == 26) { return "From"; }
else {return headers[i-1] ;}
public int getColumnCount() { return colCount; }
public int getRowCount() { return cache.size(); }
//public Class getColumnClass(int c) {
// return getValueAt(0, c).getClass();
// overloaded isCellEditable method so that it returns true
// in reference to a cell being editable.
public boolean isCellEditable(int row, int col) { return true; }
// overloaded setValyeAt which updates the data Vector and
// calls the fireTableRowsUpdated() to notify any listeners
// that data has changed and they need to redraw.
public void setValueAt(Object value, int row, int col) {
((String[])cache.elementAt(row))[col] = (String)value;
fireTableRowsUpdated(row,row);
public void getInfo () {
System.out.println("Row Count is : " + cache.size());
System.out.println("Value at 0,0 is : " + getValueAt(0,0));
// boolean res = isCellEditable(0,0);
// System.out.println("The value of the Boolean result is : " + res);
public Object getValueAt(int row, int col) {
return ((String[])cache.elementAt(row))[col];
// All the real work happens here!
// In a real application, we'd probably perform the query in a separate thread.
public void setQuery() {
cache = new Vector();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection ("jdbc:odbc:c3-erp","s3","s3");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no");
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
String[] record = new String[27];
// Now we must rebuild the headers array with the new column name
headers = new String[27];
for (int h=0; h < 27; h++) {
// headers[h-1] = meta.getColumnName(h);
headers[h] = getColumnName(h);
// and file the cache with the record from our query. This would
// be practical if we were expecting a few million records to our
// response query, but we are not so we can do this.
while(rs.next()) {
for (int i=0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
cache.addElement(record);
// Get the FIRST column of the table tableView
// TableColumn column0 = table.getColumn(cache.elementAt(0));
// Set the cell editor as non editable.
// column0.setCellEditor(new EditableCellEditor(new JComboBox(), true));
fireTableChanged(null); // notify everyone the we had a new table.
catch (Exception e) {
cache = new Vector(); // blank it out and keep going.
e.printStackTrace();
public static void main(String[] args) {
VasuTest frame = new VasuTest();
frame.pack();
frame.setVisible(true);
}When you click on the save button, you need to go through the model and retrieve the values getValueAt().
Convert to whatever type you want since getValueAt() returns type Object and update the DB. -
Can not insert/update data from table which is created from view
Hi all
I'm using Oracle database 11g
I've created table from view as the following command:
Create table table_new as select * from View_Old
I can insert/update data into table_new by command line.
But I can not Insert/update data of table_new by SI Oject Browser tool or Oracle SQL Developer tool .(read only)
Anybody tell me, what's happend? cause?
Thankyou
thiensu
Edited by: user8248216 on May 5, 2011 8:54 PM
Edited by: user8248216 on May 5, 2011 8:55 PMI can insert/update data into table_new by command line.
But I can not Insert/update data of table_new by SI Oject Browser tool or Oracle SQL Developer tool .(read only)so what is wrong with the GUI tools & why posting to DATABASE forum when that works OK? -
Error while updating data from PSA to ODS
Hi Sap Gurus,
I am facing the error while updating data from PSA to ODS in BI 7.0
The exact error message is:
The argument 'TBD' cannot be interpreted as a number
The error was triggered at the following point in the program:
GP44QSI5RV9ZA5X0NX0YMTP1FRJ 5212
Please suggest how to proceed on this issue.
Points will be awarded.Hi ,
Try to simulate the process.That can give you exact error location.
It seems like while updating few records may be no in the format of the field in which it is updated.
Regards
Rahul Bindroo -
How can we update data in LDAP server using PL/SQL.
Hi,
How can we update data in LDAP server using PL/SQL program.
Is there any sample code for refrence.
Thanks,
TarunHi Justin,
Thanks for your help. You got my correct requirements.
Tim's example returning all the attributes of current user which is admin user. Please correct me if I am wrong.
I have the following information:
the admin user and password,server info , port and ldap_base for admin.
I have uid and password for regular user, I am trying find the ldap_base for regular user, which may be different from adminuser.
Please help me.
Thanks,
Edited by: james. on Jan 12, 2009 5:39 PM -
How to update data in a xml file.
I am able to retrieve data from a xml file but not able to update data. Also how can i add or delete node from a xml file.
Hi,
For some time I have also been trying to do the same thing with no success. So far I have tried a few approaches like $.post functions $.ajax post functions and HTML5 fileWriter functions. I am not well aware of the web development techniques but as fas as I understand the post or update of the json file should be done on the serverside mainly because of security issues. I am not sure how appbuilder works entirely and if there is any way to do this.
Have you managed to find a solution ?
(P.S. my goal is to update my chart data which is of course json file. So the idea here is to get some values from the user input and update the json file values then refresh the chart and display it with the new values).
Best Regards,
A.Dyankov. -
Cannot update data in a demantra worksheet..
Hello all,
I am not able to update data in a demantra worksheet - referred to Oracle Metalink
https://metalink.oracle.com/CSP/ui/flash.html#tab=KBHome(page=KBHome&id=()),(page=KBNavigator&id=(bmDocID=459527.1&bmDocType=PROBLEM&viewingMode=1143&bmDocDsrc=KB&bmDocTitle=Worksheet%20Data%20is%20Not%20Being%20Saved%20to%20the%20Database%20-%20Error%20:%20Update%20Data%20Failed,%20Can't%20Create%20%3Cb%3EW...&from=BOOKMARK))
DocId= 459527.1
I have the same error message and I followed the steps exactly but I cannot seem to get rid of the error
Cannot create Wf process. Update Data id: ....
I have the components correctly defined, display units seems ok. Not sure why the Update Data is failing somewhere??
CheersHey there!
Make sure you restart web server (tomcat) after any changes you make in the business modeler, and before checking the worksheets. Make sure component has units associated, and series associated too.
Hope this helps,
Aaron -
FRM-40602: Cannot insert into or update data in a view
Hi all!
I have a form based on a view and I want to get rid off this message.
I set the properties blocks query only but it still doesn't work.
Does someone met with this situation?
Many thanks!Hello
I've just been messing about with a similar problem. Basically, I have a view that involves a join across two tables, I have a data block in my form that's based on the view, and I've written an INSTEAD OF trigger to insert/update/delete from the two tables.
I was getting the error message 'Cannot insert or update data in a view', and it turned out that the error was happening because the join column between the two tables was the primary key on one of the tables, but the corresponding column on the join table had no unique key on it. This meant that Oracle couldn't establish a one-to-one relationship between rows in the view and rows in the underlying tables. The column on the join table was in fact unique on that table, and adding a unique constraint on that column in the database cured the problem.
Hope that's of use.
regards
Andrew
UK -
Want to update data in a view based on multiple tables
Hi
I am facing a problem i want to update data in tables using a view. As that view is based on multiple tables so i am unable to update data. i came to know we can update table from view only if view is based on single table. so if anyone knows any alternative please let me know.
Thanx
DevinderDevinder,
The table can be updated through a view based on multiple tables, if and only if the table is a "key preserved" table. Rather than explaining myself, i avoided the burden of typing by finding the material in Oracle Docs and pasting it for you :-)
If you want a join view to be updatable, all of the following conditions must be
true:
1. The DML statement must affect only one table underlying the join.
2. For an INSERT statement, the view must not be created WITH CHECK
OPTION, and all columns into which values are inserted must come from a
key-preserved table. A key-preserved table in one for which every primary
key or unique key value in the base table is also unique in the join view.
3. For an UPDATE statement, all columns updated must be extracted from a
key-preserved table. If the view was created WITH CHECK OPTION, join
columns and columns taken from tables that are referenced more than once
in the view must be shielded from UPDATE.
4. For a DELETE statement, the join can have one and only one key-preserved
table. That table can appear more than once in the join, unless the view was
created WITH CHECK OPTION.
HTH
Naveen -
Hi,
trying to update data from a view with:
- Company (table)
- Products (table)
In a form, the user wants to update
e.g: both products.product_name and Company.company_name.
Is there a way to update a view records built on 2 tables ?
Any idea will be really appreciated
ThksAn other question on INSTEAD OF Trigger:
Base Tables:
1.
SQL> desc pcs_companies;
Name Null? Type
COMPANY_ID NOT NULL NUMBER(12)
COUNTRY VARCHAR2(350)
COMPANY_NAME VARCHAR2(320)
COMPANY_PHONE VARCHAR2 (320)
COMPANY_FAX VARCHAR2(320)
COMPANY_URL VARCHAR2(150)
UPDATED_DATE DATE
2.
SQL> desc pcs_individuals;
Name Null? Type
INDIVIDUAL_ID NOT NULL NUMBER(12)
COMPANY_ID NUMBER(12)
FIRST_NAME VARCHAR2(320)
LAST_NAME VARCHAR2(320)
LOB VARCHAR2(300)
JOB_ROLE VARCHAR2(300)
TITLE VARCHAR2(300)
GENDER VARCHAR2(3)
EMAIL VARCHAR2(720)
FAX VARCHAR2(720)
PHONE_NO VARCHAR2(720)
UPDATED_DATE DATE
COUNTRY VARCHAR2(150)
ADDRESS_1 VARCHAR2(720)
ADDRESS_2 VARCHAR2(720)
ADDRESS_3 VARCHAR2(720)
CITY VARCHAR2(720)
3. pcs_individuals.COMPANY_ID = FK, ref pcs_companies.
4.
SQL> CREATE VIEW V_PCS_COMPANY_IND
AS
SELECT
i.INDIVIDUAL_ID,
c.company_id,
c.country,
c.Company_name,
c.company_phone,
i.Company_id indiv_company_id,
i.gender,
i.first_name,
i.last_name,
i.lob,
i.job_role,
i.title,
i.email_address,
i.fax,
i.phone_no ,
i.address_1,
i.address_2,
i.address_3,
i.city
FROM
pcs_individuals i,
pcs_companies c
WHERE
i.company_id = c.company_id
5.
CREATE OR REPLACE TRIGGER PCS_ADMIN.PCS_COMP_IND_UPDATE_TR
INSTEAD OF UPDATE ON PCMS_ADMIN.V_PCS_COMPANY_IND
FOR EACH ROW
begin
update PCS_COMPANIES
set
Company_name = nvl(:new.company_name,company_name),
company_phone = nvl(:new.company_phone,company_phone)
where company_id = :new.company_id;
update PCS_INDIVIDUALS
set
gender = nvl(:new.gender,gender),
first_name = nvl(:new.first_name,first_name),
last_name = nvl(:new.last_name,last_name),
lob = nvl(:new.lob,lob),
title = nvl(:new.title,title),
email_address = nvl(:new.email_address,email_address),
phone_no = nvl(:new.phone_no,phone_no),
fax = nvl(:new.fax,fax),
country = nvl(:new.country,country),
address_1 = nvl(:new.address_1,address_1),
address_2 = nvl(:new.address_2,address_2),
address_3 = nvl(:new.address_3,address_3),
city = nvl(:new.city,city)
where company_id = :new.company_id;
end PCMS_COMP_IND_UPDATE_TR;
6.
CREATE OR REPLACE TRIGGER PCS_ADMIN.NEW_COMPANY_ID_INSERT
INSTEAD OF INSERT ON PCS_ADMIN.V_PCS_COMPANY_IND
DECLARE
ID number;
BEGIN
INSERT INTO pcs_companies (org_id)
select v_pcs_comp_id_seq.nextval
into ID
from dual;
:new.company_id = ID;
INSERT INTO pcs_individuals (company_id)
select v_pcs_comp_id_seq.nextval
into ID
from dual;
:new.company_id = ID;
end;
My question
On point 6:
Assumption:
- Company_id is PK of pcs.Company and FK in pcs.individuals
- It should be feed by sequence (v_pcs_comp_id_seq)
Now how can i insert the same value for company_id (current.v_pcs_comp_id_seq) in both pcs_companies and pcs_individuals ? I've tested it in the above INSTEAD OF Trigger.It failed.
Thks for any advice,
lamine -
Hi All,
I'm trying to write a program to update the DB informations.
For example, an Invoice Maintenance program that involve 2 tables,
Invoice Header and Invoice Details. I load the Invoice Details
records from db table to a DBGrid for user update and call a PHP
program using mx:HTTPService to write the updated data to db.
I would like to know how can I check the dbGrid that only
modified rows will pass to the HTTPService to updating? Or I need
to pass all rows one by one to HTTPService and update the records
one by one? Also is it only possible to pass one row every time
when I call the httpService or I can pass the whole dbGrid and
extract row by row in the php program?
If this problem can be solved I think I can complete the
system without any big problem (except printing ;-) )
Thanks a lot!
WilsonUsing the edit events, I would store a list of the item
indexes that have been changed. Then use that list to return and
build an xml string, and post it to the server via HttpService.
Tracy
Maybe you are looking for
-
Can't remove background image completely
Hi there, I'm making a site at the moment using the Darkroom theme but I'd like to totally remove the background image. When I go into layout and turn off page background and browser background it removes it from round the edges but not from the main
-
BPM process withour initialize task?
Hi, Is it possible to have a BPM process without initiate task? My Use Case: Pass some data to the BPM process during the instance creation. I don't find any way to pass the data during instance creation. I'm thinking of having a webservice call as f
-
BAPI_ACC_DOCUMENT_REV_CHECK
Hello, I´m using the bapi BAPI_ACC_DOCUMENT_REV_CHECK to check whether a FI document is able to be reversed. The bapi works fine, but it blocks the FI document till the programm finishes, so I can´t reverse the document if necesary. How can I unbl
-
Hello, In our XI-PROD system I found 24 system users. In "system users" I talked about these users: DDIC J2EE_ADMIN J2EE_GUEST LSADMIN OSS SAP* SAPCPIC SAPJSF SAPPORTAL SOLMAN SUPPORT TMSADM WF-BATCH XIAFUSER XIAPPLUSER XIDIRUSER XIISUSER XILDUSER XI
-
Prime 1.3: Image_Distribution fails
Hello, I've upgraded from Cisco Prime Infrastructure 1.2 to 1.3, the upgrade process ran without any errors. Now I've tested the image distribution and it fails always and I get these error messages when Prime has to "Erase Flash Before Distribution"