I'm using DefaultTableModel in NetBeans in showing my records from MySQL database. My data is able to display, but what I want is that to display a checkbox column at the end of my table.
I understand it needs to be overridden, but I don't know how and where to start. I see tons of example from the internet but they are using static string data, not from database. Until now I still don't get it. A help will be much appreciated.
Below is my sample code.
try {
conn = DatabaseConnect.connect();
ps = conn.prepareStatement("SELECT productID, name, quantity, price, checked FROM tbl_inventory");
rs = ps.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch(SQLException ex) {
}
jTable2 is able to display my records from tbl_inventory. The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The easiest way is to convert the "checked" data to a Boolean value as you create the TableModel. Then the default renderer/editor will be used.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
This means you can't use the above method. You need to copy the data yourself and do the conversion on the checked column.
Check out Table From DataBase. The last example Table From Database Example shows how to copy the data without any conversion.
You will need to modify the code with something like:
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
if (i == ?) // convert checked column
{
int value = rs.getInt(i);
row.addElement( value == 0 ? Boolean.FALSE : Boolean.TRUE );
}
else
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
Related
Does each Cell in returned Result object have same timestamp?
Is it save to do something like this?
try (Table table = connectionFactory.getConnection().getTable(TABLE)) {
try (ResultScanner scanner = table.getScanner(generateScan(systemId))) {
for (Result result: scanner) {
if (result == null) {
break;
}
long ts = result.rawCells()[0].getTimestamp();
System.out.println("Row last update time: " + ts);
}
}
}
Will I obtain time stamp of the last row modification?
Cells in Result can have different timestamp. Each cell is a combination of CF:C:V, where CF is column family, C is a column and V is a version. Even if you store only 1 version, you can update columns of a cell independently. Cell timestamp is updated when you store something.
For example you have table user with cf:main and two columns name and age. If you update both columns in same Put they will have same timetamp. If you update only name column, timestamps will be different. So generally it depends on your usage pattern.
I use the below approach to determine my result set is not empty and proceed to do assertions on the values.
...
resultSet = statement.executeQuery("select count(*) as rowCount from tbName where...");
while (resultSet.next()) {
rowCount = Integer.parseInt(resultSet.getString("rowCount"));
}
Assert.assertTrue(rowCount > 0);
resultSet = statement.executeQuery("select * from tbName where ...");
while (resultSet.next()) {
//do some assertions on values here.
}
...
Is there anyway to get the number of rows directly from the resultSet directly in a single query? Something like the below?
resultSet = statement.executeQuery("select * from tbName where ...");
if( resultSet.count/length/size > 0) {
}
You can change the query to include a column with the row count:
select t.*, count(*) over () as row_count
from tbName t
where ...
then you can get the count using
int rowCount rs.getInt("row_count");
Note that you won't get a 0 count because that means the actual query did not return anything in the first place. So you can't use that to verify if your query returned anything. If you only want to check if the result is empty, use next()
resultSet = statement.executeQuery(".....");
if (resultSet.next()) {
// at least one row returned
} else {
// no rows returned at all
}
Btw: you should always use the getXXX() method that matches the column's data type. Using getString() on all columns is not a good idea.
1) Moves the cursor to the last row: resultset.last();
2)Retrieves the current row number: int count = resultset.getRow();
Tips:
It's based on you create a statement via calling function "
Statement createStatement(int resultSetType,int resultSetConcurrency)
throws SQLException"
to gernerate a scrollable resultSet.
There are two ways to get number of rows.
1) if you want to check the number of rows exist in table you may use count query.
2) if you want to count number of rows in a result set you have to traverse that result set to count rows.
I want to shown a JTable with Value from database, but in some coloumn that calculate with a formulation. for excample like this :
Table in database :
from that table i want to shown in JTable, with calculation :
coloumn Pendidikan and Skripsi, value is direct from database.
column Penelitian and MK, value from database calculate with formula value in row minus average from that coloumn. the result shown in table:
so, how to make it like that?, but the formula building in java
this my code to show data to JTable:
tabModel = new DefaultTableModel(null,header);
tabel.setModel(tabModel);
try { String query = "SELECT NIP,Pendidikan,Penelitian,MK,Skripsi FROM table1 group by NIP";
java.sql.Statement Stat = Connect.createStatement();
java.sql.ResultSet rs = Stat.executeQuery(query);
while (rs.next()) {
String nip = rs.getString("NIP");
String bidang = rs.getString("Bidang");
String pendidikan = rs.getString("Pendidikan");
String penelitian = rs.getString("Penelitian");
String mk = rs.getString("MK");
String skripsi = rs.getString("Skripsi");
String[] dataTampil = {nip,bidang,pendidikan,penelitian,mk,skripsi};
tabModel.addRow(dataTampil);
tabel.setModel(tabModel);
}
}catch(Exception e){}
}
but, i can't calculate the table with differnt formula for every coloumn.
for coloumn Pendidikan and skripsi the value direct from database, but for coloumn Penelitian and MK the value form Value in Row minus Average for thats coloumn.
You should first be using rs.getInt() since as your sample shows in your original question, that they are in fact integers. Once you have them as Integers you can do whatever calculations you need to for Penelitian and MK instead of using the ones from the database. In other words, for these two variables, set them to whatever calculation they should be instead of just using the value from rs.getInt()
I am doing a school project and I am having trouble with storing the data from a resultset in a JTable. Previously I had used DButils but now I am wondering if there is a way to do the same thing without having to used external class files or if it is easier to use DButils.
The data is coming from only one table and all that needs to happen is the data must be displayed in the JTable.
I would post my code here but I have looked and the only tutorials I could find were ones on how to populate a JTable using and Object [][]. I am using JDBC to create the connection.
Thanks in advance.
Well this will require several steps.
I will explain my way, which is good for very large sets, but a little complicated if you only want to show a few lines. Still I'm sure it will help you. This method will load the required records on the fly, not the whole set before hand. It creates the illusion of having the whole set, but with out having to wait for a lengthy load.
1) Ok, first, let's assume that we have a nice JFrame that you can display, to start with. So first I will add a JScrollPane, and inside it I will add a JTable. Run it and make sure you have a nice window with an empty JTable inside scroll bars.
2) So next you need a data source for the JTable. Since a JTable is a very generic component not made specifically for SQL resultSets, it requires a data source that implements javax.swing.table.AbstractTableModel which has nothing to do with SQL. So we will now create a TableModelClass which will implement AbstractTableModel, then we will add this to the JTable and it will start working. Of course, the trick is to implement all of AbstractTableModel's methods that get data by using our SQL result set, and this is up to you. From here is my suggestion ->
3) Since this will be dynamic, we will not need to load all the data before hand, but we need an initial set to display. I will have a Object [][] of a fixed size, lets say 200 - 300 rows. So I will initially execute the SQL and fill the array with the buffer size of 200-300 rows. How much to cache will depend on 2 things: 1 It shall be enough to get all the data for the current display size of the JTable, and 2, it should be small enough so that as we scroll and get subsequent caches it executes very fast.
4) Now let's begin implementing all AbstractTableModel's interface methods.
5) First we look at the initial result set and report the number of columns. Just add a class variable, set the column count and return it using: public int getColumnCount( ). This will not change from now.
6) Also looking at the result set metadata, make a list variable in the class and add the column names returned in the meta data. Using this list return the column names in "getColumnName( int col )". Of course, the col index is the column position in the result set.
7) Now lets do "int getRowCount( )". Inside the TableModelClass keep a variable to contain the rowCount and return it in this method. TIP: Don’t worry for now, set it to a fixed large number like 65000, this will let scroll as you dynamically load the records. Once we hit the end we will set the number to the real value and the scroll pane will adjust to the correct proportions. Trust me, it works ok.
8) Now comes the fun part. As the JTable presents the first "page" of the table and as the user scrolls it will begin calling "getValueAt( int row, int col )". This will map directly to our Object[][], but since we only have a cache, and not the whole table, as the user scrolls down we will need to fetch more data. I do this:
public Object getValueAt( int row, int col )
{
// load failed before, no more trying...
if( loadExceptionOccur || ( row >= visualTableSize ) ) return( "" );
// check if requested row is OUT of cache …
try{
if(
// less than cache lower limit...
( ( row < startRow )
||
// Beyond cache upper limit...
( row >= startRow + tableDataCache.size()) )
// Stop unnecessary loading, because of Jtable readjusting
// its visual table size and redrawing the entire table.
&& !tableRedraw
// yes, get new cache...
){
load( row ); // <- below is code
}
// now we now the row is in cache, so ->
// verify requested cell in cache, or beyond data rows,
if(
// greater than lower limit
( row >= startRow )
&&
// less than upper limit...
( row < ( startRow + tableDataCache.size() ) )
){
tableRedraw = false;
// just get the data from the cache. tableDataCache is just your Object[][] array…
Object cellValue = ( ( recordClass ) tableDataCache.get( row-startRow ) ).getValueAt( col );
return ( cellValue );
}
else{
// just show as blank
return( "" );
}
}
catch( Exception error ){
…
In case of a cache miss you need to reload a cache of data. I will normally load some rows before the requested row and some beyond, at least for a JTable page size, so that we only go once to the db to render a screen. The bigger the cache the more scrolling before loading, but the larger the time it takes to load a cache. If you fine tune it, the cache processing might be almost unnoticeable.
Here is the implementation of "load":
public void load( int rowIndex )
throws KExceptionClass
{
// calculate start of new cache, if not enough rows for top half of cache
// then start from 0
int halfCache = cacheSize / 2 ;
int DBStartRow = 0;
if( rowIndex > halfCache ) DBStartRow = rowIndex - halfCache;
//Do query to DB
try{
SQLP.load( DBStartRow, cacheSize ); // <- using jdbc load from DbsartRow as many rows as cacheSize. Some sample SQL paging code below ->
}catch( Exception loadError ){
// if the database fails or something do this, so you don’t get a billion errors for each cell. ->
//set load failed flag, kill window
loadExceptionOccur = true;
visualTableSize = 0;
tableDataCache = new ArrayList< recordClass >();
fireTableDataChanged(); // clear the Jtable
// log error
log.log( this, KMetaUtilsClass.getStackTrace( loadError ) );
// show error message
throw new KExceptionClass( "Could not load table data! " , loadError );
}
//Load rows into the cache list.
//Key field values are in the cache list as the last field in each record.
tableDataCache.clear(); // the Object [][], wrapped in class
while( SQLPreprocessor.nextRowValue() ) {
SQL.fetch( record ); //<- get JDBC rows to table cache
tableDataCache.add( record ); // this uses my library, change to JDBC or what ever you use to access SQL
}
log.log( this, "cacheList size = " + tableDataCache.size());
//---------
if(
// Last requested row number
( DBStartRow + cacheSize ) >
// Last replied row number
( SQLPreprocessor.getloadedStartRowIndex() + SQLPreprocessor.getloadedRowCount() )
){
// It is the end of table.
// The visual table is readjusted accordingly.
visualTableSize = SQLPreprocessor.getloadedStartRowIndex() + SQLPreprocessor.getloadedRowCount();
fireTableDataChanged();
tableRedraw = true;
}
startRow = SQLPreprocessor.getloadedStartRowIndex();
log.log( this, "visualTableSize = " + visualTableSize );
}
Ok this will dynamically load the data in small caches which will give the impression of having the whole set.
If the user scrolls to the middle or all the way to the end, the JTable will ask only for the data need to display not all the rows as it moves, so, if you have a 10K row table, but the JTable is only 20 rows high, a scroll to the end will only take 40 - 50 rows to load. Pretty nice. Your users will be impressed.
Now the thing is that the load assumes that you have a SQL cursor that moves forward and backwards by row number. This simple thing is quite a challenge in SQL. For Oracle check : http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html
Ok, hope that helps.--
Of course there's a way: iterate through the ResultSet and add what you find to the Object [][] array that gets passed to the JTable. There's one row in the 2D array for each row in the ResultSet; the columns are the values.
The problem you'll have is that you won't know how many rows came back without iterating through it. That's why loading it into a Map<String, Object> might be a better idea.
Here's an example showing how to do it. You'll find that method (and more) at my answer to this question:
java sql connections via class
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException {
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try {
if (rs != null) {
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i) {
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
} finally {
close(rs);
}
return results;
}
I'm new to JTable.I'm working in Swings using JTable & Toplink(JPA). I have two buttons "add Row", "Del Row" and I have some records displayed from db. when ever "add row" is clicked a new record, row header should be added to JTable with an auto increment number displayed in sequential order to the JTable Row Header.
During deletion using "Del row " button the record has to be deleted & not its corresponding header so that next rows got updated to the previous headers & the auto increment number remain unchanged and always be in sequence.
please help me on this regard.
Thanks in advance,
Chandu
As you are new to JTable, I'd start with How to Use Tables. As suggested there, I'd extend AbstractTableModel, overriding getValueAt(), setValueAt(), getRowCount(), etc. to use the corresponding JPA entity and controller classes and methods. The NetBeans IDE, for example, can generate such classes automatically. There is also a feature to bind the classes to Swing components, including JTable and JList, but I haven't tried it.
If the row id is an auto increment number managed by the database, I'm not sure there's a reliable way to maintain the appearance of sequential order in a multi-user environment. If the field is displayed at all, isCellEditable() should probably return false for that column. Is that what you mean by Row Header?
Addendum: See also What’s the best way get the ID of the item just inserted?
Do you mean like this?
likeThis http://img705.imageshack.us/img705/8920/screenshot7ry.png
When a new record is added its id is set as a row header ( as in records, 1,2,3 ) and when a record is deleted, the row header remains, but the information is gone ( as in records 4,5 which use to have data, but after being removed only leave the id )
IF that's what you mean.
What you have to do is create two table models, one wrapping the other.
The only functionality of the wrapper will be to show an extra column ( the id ) and keep an internal "copy" of the data.
When a row is added, the wrapper will get a new record, it will assign a new id and then it will take all the fields and copy the value into his own data and then will forward it to the wrapped table model.
When a row is removed, the wrapper will not remove its own record, it will only clean up ( set to "" ) the column values and will keep the id column. Then it will forward the event to the wrapped column which in turn will actually remove the row.
Something like the following noncompiling-java
// Wrapper table model
class IdTableModel implements TableModelListener {
TableModel original;
// Analog to: Object[][]
List<List<Object> data = new ArrayList<List<Object>();
// will take a copy of the data in original
public IdTableModel( TableModel original ) {
this.original = original;
// fillData with values from original
for( int row = 0 ; row < original.getRowCount(); row++ ) {
List<Object> shadowRow = new ArrayList<Object>();
shadowRow.add( row ); // the id
// copy the values from original to this shadow
for( int column = 0 ; column < original.getColumnCount(); column++ ) {
shadowRow.add( original.getValueAt(row,i));
}
// add the shadow to the data
data.add( shadowRow );
}
original.addTableModelListener( this );
}
// for Object getValueAt( x, y ) get the data from your "data" not from the original
....
//Here's the magic. this wapper will be a listener of the original
// then this method will be invoked when the original gets more data
// or when it is removed.....
public void tableChanged( TableEvent e ) {
int row = e.getFirstRow();
List<Object> shadowRow = data.get( row);
switch( e.getType() ) {
case TableEvent.INSERT:
if( ( shadowRow =) == null ) {
// there wasn't shadow data at that position
data.add( ( shadowRow = new ArrayList<Object>()));
}
// takevalues from original
shadowRow.add( row ); // the id
for( int i = 0 ; i < original.getColumnCount();i++ ) {
shadowRow.add( original.getValueAt(row,i));
}
break;
case TableEvent.UPDATE:
// similar to insert, but you don't create a new row
// takevalues from original
for( int i = 0 ; i < original.getColumnCount();i++ ) {
shadowRow.set( i+1, original.getValueAt(row,i));
}
break;
case TableEvent.DELETE:
// You don't delete your shadow rows, but just clean it up
for( int i = 0 ; i < original.getColumnCount();i++ ) {
shadowRow.set( i+1, "");
}
break;
}
// forward calls to the original
public int getColumnCount(){
return original.getColumnCount()+1;
}
public String getColumnName( int columnIndex ) {
if( columnIndex == 0 ) {
return "id";
} else {
return original.getColumnName( columnIndex -1 );
}
}
// and so on for, isEditable etc. etc
}
Well that was much more code that what I initially wanted.
The idea is to have a table model wrapper that adds that fictional id column for you and don't delete it, you just use it like this:
JTable yourTable = new JTable( new IdTableModel( originalTableModel ));
If nothing of what I said make sense to you, start reading this: How to use tables
This page might be what you're looking for: http://www.chka.de/swing/table/row-headers/JTable.html