Jtable, sql, default table model
Hi all,
I need help. How do I create JTable, generaly Default table model and query which will work with the database. Thx.
Look to this example
[http://jfxstudio.wordpress.com/2009/05/25/the-graphic-database-front-end-ii/|http://jfxstudio.wordpress.com/2009/05/25/the-graphic-database-front-end-ii/]
tables, database and advanced graphics
Similar Messages
-
Is it posiible to paging up paging down in Jtable using Default Table Model
Hi All!
Is it possible to do Page up and Page down in JTable using Default Tble Model?
Kindly reply!yes
it is posiible to paging up paging down in Jtable using Default Table Model. just go thru the JAVA API you will get the results. -
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);
} -
PageUp/PageDown By using 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.Hi,
could you please avoid double posting:
http://forum.java.sun.com/thread.jsp?forum=57&thread=566380&tstart=0&trange=15
especially with different subjects.
It considerably reduces the overall efficiency as people will try to
help you while the answer could already have been given in the another thread.
If you want to push up the stack your message, reply to it,
post more code, list the ideas that you've envisaged and so on.
regards. -
Setting row identifiers in default table model
hey i'm making a default table model and i cant figure out how to make a row have an identifier. the column one is setColumnIdentifiers but there isn't a code that i could find for a row.. please help thanx kevin
You are correct, JTable does not support a TableRowModel, therefore it does not support setRowIdentifiers.
I'm not sure exactly what your requirement is so its hard to make a suggestion. You could add an extra column to your table to contain a row identifier. You could then remove this column from the TableColumnModel to prevent this column from being painted. This [url http://forum.java.sun.com/thread.jsp?forum=31&thread=411506]thread shows how to remove a column from the table. -
Transfer Data from a JTable to the table model
Hi
I' looking for a simple method to transfer the last user input in a table to the table model.
For example:
In a Dialog the user insert in a JTable a few values and leaves with OK. But the last input is not saved in the model. It is just saved after selecting a new field in the JTable before leaving the Dialog.
Is there a call to transfer all input to the model?
Thanks
Guidoclass MyJTable extends JTable (
public boolean validateInput() {
if(isEditing()) {
return cellEditor.stopCellEditing();
return true;
Call this method whenever you want the input value to be stored in the table model. The return value can be false if the input isn't valid, this will depend on the cell editor.
The idea is:
Ask if the table has an editor activated. (isEditing())
If so, request the editor to store the value in the model.
I haven't prouved the code, sorry, but I hope you get the idea and helps. -
JButton in JTable with custom table model
Hi!
I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
thanksYes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 3) {
return false;
} else {
return true;
}A pretty stupid thing when you want to edit the 3rd column... -
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 -
How to add image in jtable header using 'Default table model'
Hi,
I created a table using "DefaultTableModel".
im able to add images in table cells but not in 'table header'.
i added inages in table by overriding "getColumnClass" of the DefaultTableModel.
But what to do for headers?
please help.
Thanks in advance.The 'Java 5 tutorial' is really an outstanding oneI should note the the current tutorial on the Sun website has bee updated for Java 6. It contains updates to reflect the changes made in JDK6. Once of the changes is that sorting of tables is now supported directly which is why I needed to give you the link to the old tutorial.
http://java.sun.com/docs/books/tutorial/uiswing/TOC.html -
Help for adjusting columns of a JTAble in a Table Model
Hello community,
In order to have a good display of by DataBase in a JTable, I've wrote some code to adjust columns in function of datas. Those datas are displayed with a TableModel ( which I've declared in a class JDBCAdapter ).
When I start my application, I call adjustColumns(), and all is great but when I add information to my DB and display it, the columns of my JTable return to default width...
So I want to incorporate my function adjustColumns in my TableModel, and I need help...
void adjustColumns()
// Ajuste les colonnes aux donnes pour que tout soit visible
int nbRow,nbCol;
nbRow = JTable1.getRowCount();
nbCol = test.getColumnCount();
for ( int i = 0; i < nbCol; i++ )
com.sun.java.swing.table.TableColumn column = null;
column = JTable1.getColumnModel().getColumn(i);
int dataLength = 0;
for ( int j = 0; j< nbRow; j++ )
FontMetrics fm;
int dataLengthTmp;
String valueTable;
fm = JTable1.getFontMetrics(JTable1.getFont());
if ( test.getValueAt(j, i) == null )
System.out.println("Valeur nulle...");
dataLengthTmp = 0;
else
valueTable = test.getValueAt(j, i).toString();
dataLengthTmp = fm.stringWidth(valueTable);
System.out.println(valueTable + " = " + dataLengthTmp);
if ( dataLengthTmp > dataLength )
dataLength = dataLengthTmp;
if ( dataLength != 0 )
column.setWidth(dataLength + 5);
else
column.sizeWidthToFit();
JTable1.setModel(test);
JTable1.repaint();
import java.util.Vector;
import java.sql.*;
import com.sun.java.swing.table.AbstractTableModel;
import com.sun.java.swing.event.TableModelEvent;
public class JDBCAdapter extends AbstractTableModel {
Connection connection;
Statement statement;
ResultSet resultSet;
String[] columnNames = {};
Vector rows = new Vector();
ResultSetMetaData metaData;
public JDBCAdapter(String url, String driverName,
String user, String passwd) {
try {
Class.forName(driverName);
System.out.println("Ouverture de la connexion a la base de donnee...");
connection = DriverManager.getConnection(url, user, passwd);
statement = connection.createStatement();
catch (ClassNotFoundException ex) {
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
catch (SQLException ex) {
System.err.println("Cannot connect to this database.");
System.err.println(ex);
public void executeQuery(String query) {
if (connection == null || statement == null) {
System.err.println("There is no database to execute the query.");
return;
try {
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
for(int column = 0; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnLabel(column+1);
// Get all rows.
rows = new Vector();
while (resultSet.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement(resultSet.getObject(i));
rows.addElement(newRow);
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
fireTableChanged(null); // Tell the listeners a new table has arrived.
catch (SQLException ex) {
System.err.println(ex+" query = "+query);
public void executeUpdate(String query) {
if (connection == null || statement == null) {
System.err.println("There is no database to execute the query.");
return;
try {
statement.executeUpdate(query);
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
fireTableChanged(null); // Tell the listeners a new table has arrived.
catch (SQLException ex) {
System.err.println(ex+" query = "+query);
public void close() throws SQLException {
System.out.println("Fermeture de la connection a la base de donnee... Bye !");
resultSet.close();
statement.close();
connection.close();
protected void finalize() throws Throwable {
close();
super.finalize();
// Implementation of the TableModel Interface
// MetaData
public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
} else {
return "";
public Class getColumnClass(int column) {
int type;
try {
type = metaData.getColumnType(column+1);
catch (SQLException e) {
return super.getColumnClass(column);
switch(type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BIT:
return Boolean.class;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Integer.class;
case Types.BIGINT:
return Long.class;
case Types.FLOAT:
case Types.DOUBLE:
return Double.class;
case Types.DATE:
return java.sql.Date.class;
default:
return Object.class;
public boolean isCellEditable(int row, int column) {
try {
return metaData.isWritable(column+1);
catch (SQLException e) {
return false;
public int getColumnCount() {
return columnNames.length;
// Data methods
public int getRowCount() {
return rows.size();
public Object getValueAt(int aRow, int aColumn) {
Vector row = (Vector)rows.elementAt(aRow);
return row.elementAt(aColumn);
public String dbRepresentation(int column, Object value) {
int type;
if (value == null) {
return "null";
try {
type = metaData.getColumnType(column+1);
catch (SQLException e) {
return value.toString();
switch(type) {
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
return value.toString();
case Types.BIT:
return ((Boolean)value).booleanValue() ? "1" : "0";
case Types.DATE:
return value.toString(); // This will need some conversion.
default:
return "\""+value.toString()+"\"";
public void setValueAt(Object value, int row, int column) {
try {
String tableName = metaData.getTableName(column+1);
// Some of the drivers seem buggy, tableName should not be null.
if (tableName == null) {
System.out.println("Table name returned null.");
String columnName = getColumnName(column);
String query =
"update "+tableName+
" set "+columnName+" = "+dbRepresentation(column, value)+
" where ";
// We don't have a model of the schema so we don't know the
// primary keys or which columns to lock on. To demonstrate
// that editing is possible, we'll just lock on everything.
for(int col = 0; col<getColumnCount(); col++) {
String colName = getColumnName(col);
if (colName.equals("")) {
continue;
if (col != 0) {
query = query + " and ";
query = query + colName +" = "+
dbRepresentation(col, getValueAt(row, col));
System.out.println(query);
System.out.println("Not sending update to database");
// statement.executeQuery(query);
catch (SQLException e) {
// e.printStackTrace();
System.err.println("Update failed");
Vector dataRow = (Vector)rows.elementAt(row);
dataRow.setElementAt(value, column);
Thanks to help me.Hi,
OK. I have read your code sample again. It looks like the JDBCAdapter class is reloading table data in the executeQuery method. Why not call adjustColumns at the end of this method after the new rows and columns are loaded? Perhaps it also should be called at the end of executeUpdate. Have you tried doing that?
I would still set
JTable1.setAutoCreateColumnsFromModel (false); to prevent Java from readjusting the size automatically at some other time.
regards,
Terry -
Hi All,
can u tell me how to use table model or default table model. where i can references about it???
thanks for all[http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data]
-
Copyig Data from a TABLE MODEL (TABLE) TO A FILE
Hi guys,
I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
DefaultTableModel model = new DefaultTableModel();
JTable table;
public basic()
super();
model.addColumn("Full Name");
model.addColumn("House No");
model.addColumn("Address");
model.addColumn("Town/County");
model.addColumn("Postcode");
model.addColumn("Telephone Number");
model.addColumn("Email Address");
String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
model.addRow(socrates);
/**This is the main setup for the Address Book
*This has the main settings for the size, title
*And main features of the Address book.
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(new Dimension(800, 600));
this.setTitle("Large Print Address Book");
this.setLayout(new FlowLayout ());
//Main Application Parts
JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
welcome.setFont(arial20);
this.add(welcome);
//Menu Bar
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
//Table
table = new JTable(model);
this.add(table);
JMenu fm = new JMenu("File");
fm.setFont(arial20);
mb.add(fm);
//Menu Items
JMenuItem Add = new JMenuItem("Add Record");
Add.setFont(arial20);
Add.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
addw a = new addw();
fm.add(Add);
//Import from a file
JMenuItem inp = new JMenuItem("Import Records");
inp.setFont(arial20);
inp.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
//Opens Import Window.
inportw i = new inportw();
fm.add(inp);
JMenuItem quit = new JMenuItem("Exit");
quit.setFont(arial20);
fm.add(quit);
quit.addActionListener(this);
class inportw extends JFrame
//*Add Window Properties and Settings
public inportw ()
this.setSize(new Dimension(400, 150));
this.setTitle("Inport Records");
this.setLayout(new FlowLayout ());
this.setVisible(true);
//Nmae
JLabel error_note = new JLabel("Error Here - Need to make table final!?");
error_note.setFont(arial20);
this.add(error_note);
//Add Button
JButton binport = new JButton("Inport");
binport.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
ArrayList data = new ArrayList();
this.add(binport);
public void actionPerformed(ActionEvent e)
System.out.println("Application Exit");
System.exit(0);
public static void main(String[] args)
basic b = new basic();
The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
A complete peace of code would be helpfull that would do this for me. Thankyou guys.Rite then,
In answer to both post yes i have done my own homework if thats what you wont to call it.
And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
//Export Button - Export Window
JButton bexport = new JButton("Export (BUAB)");
bexport.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("Export Pressed ");
try
FileWriter file = new FileWriter("AddressData.txt");
BufferedWriter out = new BufferedWriter(file);
out.write("AddressBook data File");
out.close();
catch (Exception ei)
System.err.println("Error: " + ei.getMessage());
this.add(bexport);This is the export button,
I think the code for the table model should be something like this:
I wont to do something like this
model.getModel().getValueAt(0, 0);
Arrylist data = new arrylist();
try
FileWriter ffile = new FileWriter("AddressData.txt");
BufferedWriter out = new BufferedWriter(file);
out.write(data);
out.close();
catch (Exception ei)
System.err.println("Error: " + ei.getMessage());
} Im not 100% sure how to get the information from the model into the arrylist, though a loop.
If there is a section of a webpage that may help could someone please post it for me.
Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
If no one wonts to help then that fine with me ! -
How to Add and delete a row while using Abstract Table Model
Hi,
I need to do the following functionalities in JTable.I've done tht but a small problem.
1. Adding a row (Using addRow() method from DefaultTableModel).
2. Deleting a row(Using setRowCount() method from Default Table Model).
3. Sorting the table based on the selection of column(Using TableSorter which is using AbstracTableModel).
As the sorting is mandatory i've to change my model to Abtract Table Model
The problem is this Abstract Table Model doesn't have any methods to Add a row or deleting a row (setRowCount()).If anybody has written any utility method for this using Abstract Table Model help me.Using TableSorter which is using AbstracTableModel).If your talking about the TableSorter class from the Swing tutorial, then you create the TableSorter class by passing it a TableModel. There is no reason you can't use the DefaltTableModel.
I changed the code in TableSorterDemo as follows:
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new BigDecimal(1), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new BigDecimal(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new BigDecimal(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new BigDecimal(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new BigDecimal(10), new Boolean(false)}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
TableSorter sorter = new TableSorter(model);
// TableSorter sorter = new TableSorter(new MyTableModel()); //ADDED THIS -
hi all
i have a list of doubts
im designing an appln which displays a JTable , the data for the table is got from the database server, im using the Abstracttable model
i went for abstract table model since in my application the contents of the table very frequently , so i can handle it using the
firetabledatachanged or some fire functions
1)my doubt is where and when we have to use the abstracttable model and when we have to go for default table model
2) Now im keeping a button in my application if i press that ,a new row
have to be added at the end of that table , how i can carry it on using abstract table model(i think ,In default table model we can do it using
addrow ( )or insert row())
thnks in advance
keonHi,
You can use DefaultTableModel in place of AbstractTableModel, coz the method fireDataChanged() which you need is present in DefaultTableModel also(inherited from AbstractTableModel , since it is its parent model), apart from that DefaultTableModel gives you convenience methods such as addRow(), insertRow(), removeRow(), which you can override to your convenience.
However the only constraint is that the DefaultTableModel uses a Vector of Vectors to hold its Model/Data, if you want a different datastructure to be used as underlying model then you should be careful enough to implement all the methods that you are going to call on that instance of DefaultTableModel, this is becuase all the default implementations of the methods of DefaultTableModel assume that the underlying datastructure is a Vector, so if you replace it with a Map or a List then you should provide appropriate implementation to all its methods that manipulate the underlying datastructure -
JTable with custom column model and table model not showing table header
Hello,
I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
Thanks for your help.
import javax.swing.*;
import javax.swing.table.*;
public class Test1 extends JFrame
public static void main(String args[])
JTable table;
TableColumnModel colModel=createTestColumnModel();
TestTableModel tableModel=new TestTableModel();
Test1 frame=new Test1();
table=new JTable(tableModel, colModel);
frame.getContentPane().add(new JScrollPane(table));
frame.setSize(200,200);
frame.setVisible(true);
private static DefaultTableColumnModel createTestColumnModel()
DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
columnModel.addColumn(new TableColumn(0));
return columnModel;
static class TestTableModel extends AbstractTableModel
public int getColumnCount()
return 1;
public Class<?> getColumnClass(int columnIndex)
return String.class;
public String getColumnName(int column)
return "col";
public int getRowCount()
return 1;
public Object getValueAt(int row, int col)
return "test";
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
}Edited by: 802416 on 14-Oct-2010 04:29
addedKleopatra wrote:
jduprez wrote:
See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
When the TableColumn is created, the default headerValue is null
So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
- it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
- furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
Thanks for the opportunity to have some fun :-)
JeanetteNo problem, thanks for the insight :)
Maybe you are looking for
-
If I signed from two different apple ID on my phone, and now my Icloude is not working?? because whenever I tried to sign in the device alert me that there is too many apple ID on the Iphone? I need to know how I can delete the Apple ID for good??
-
Hi, Does anyone has any idea on how to do SSL based TCP/IP communication. Any help/ideas/suggestions would be appreciated. Thanks, Runjhun Agarwal.
-
Call phone from app How can I call phone number from my app. I use adobe flash cs 5.5 and actionscript 3.0
-
3G, IOS4.2.1 and Iphoto 11 (9.1)
Just recently, I have been unable to sync a selected album (the only one I want) from iPhoto11 onto my iPhone. The sync starts OK and then the warning appears "the required file cannot be found". Syncing on the iPad works fine, so am stumped...any id
-
Importing a data cd...
my friend burned me a dvr rw cd and choose the data cd feature to fit more music on it, how do i import that into my library? I highlighted all the songs and converted them but I do not know where to go from there... anyone know what to do?