Creating JTable Row Header - java

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

Related

Is there a way to pass back 2 different data types from a method in java?

I am trying to populate an empty array in the first column with ordered numbers and write this back. This works, but I need the row location passed back too for reference in another method.
// Generate a customer/order number.
public static String[][] gen_cust_number(String[][] cust_order, int order_location)
{
for(int row = 0; row < cust_order.length; row++)
{
if (cust_order[row][0] == null)
{
cust_order[row][0] = Integer.toString(row + 1000);
order_location = row;
Gen.p("\n\n\tYour order number is : " + cust_order[row][0]);
break;
}
}
return cust_order;
}
I'm not very familiar with working with objects, pairs, and whatnot as I am still learning but have done some searching on it and am stumped in understanding how to do it.
I'm not 100% sure with what you're trying to achieve, but by reading the code I think what get_cust_number should do is
Generate new order to the very first empty order list.
Return the new order list and its index.
If this is right, you don't have to pass the String[][] back because the reference of this instance is what the caller side already know as it's passed in the parameters.
You can also remove the order_location param as it's never read inside the method.
So what you can do to make it work is to
Remove the order_location from params.
Return the index of added order instead of the array itself.
This results in the following code.
// Generate a customer/order number.
public static int gen_cust_number(String[][] cust_order)
{
for(int row = 0; row < cust_order.length; row++)
{
if (cust_order[row][0] == null)
{
cust_order[row][0] = Integer.toString(row + 1000);
Gen.p("\n\n\tYour order number is : " + cust_order[row][0]);
return row;
}
}
// cust_order is full
return -1;
}
In the calling side, you can do the following:
String[][] cust_order = /* Some orders according to your logic. */;
int cust_order_count = /* Number of the orders generated. */;
// Generate the order and this will be the new number of orders.
cust_order_count = gen_cust_number(cust_order);

Insert checkbox in DefaultTableModel using database data

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 );
}

ComboBox with multiple columns - search by key

I have a JComboBox that displays 2 columns. Now I would like to enable to search by key on all columns. Example:
Column1 | Column2
A1 | S1
A2 | B1
A3 | P1
The search by key on the first column works fine with default Implementation of KeySelectionManager for JComboBox. However, I would also like to be able to search for the second column as well, meaning when I press 'B' the second item is selected.
I have taken a look at the KeySelectionManager but didn't find anything useful. I have attached a screenshot of the ComboBox to show what I mean.
Thanks for any pointers.
Check KeySelectionManager implemetation in JComboBox's source code
class DefaultKeySelectionManager implements KeySelectionManager, Serializable {
public int selectionForKey(char aKey,ComboBoxModel aModel) {
....
for ( i = ++currentSelection, c = aModel.getSize() ; i < c ; i++ ) {
Object elem = aModel.getElementAt(i);
if (elem != null && elem.toString() != null) {
v = elem.toString().toLowerCase();
if ( v.length() > 0 && v.charAt(0) == aKey )
return i;
}
}
So try to override your model's Element's class toString() method to include both columns.
If you display two columns in the combo box then you must be using a custom renderer.
So maybe the approach presented in Combo Box With Custom Renderer can help. The solution in the blog combines the renderer and KeySelectionManager into a single class. All you need to do is implement the getDisplayValue() method to return the text to renderer.
In your case you have two pieces of text to render and search, so you might be able to just change the getDisplayValue() method to return List of text you want to display.
Then the renderer can use both items in the List and the getNextMatch() method of the class would also be modified to check each item in the list for a match.

Verifying row is not empty before adding new row

I'm developing a tool which is supposed to save the content from a JTable to a CSV file, I have this "add row" button to add a new row, but I need the last row to be filled on every cell and then be allowed to add a new row.
Here is the code I have, but this doesn't create the new row nor throw any errors on console.
private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
for(int i=0;i<=jTable1.getColumnCount();i++){
if(jTable1.isRowSelected(jTable1.getRowCount())){
do{
model.insertRow(jTable1.getRowCount(), new Object[]{});
} while(jTable1.getValueAt(jTable1.getRowCount(), i).equals(""));
}
}
}
Okay, so what you seem to be saying is, the user should not be allowed to add a new row until the last row is fully completed...
You existing loop doesn't make sense, basically, for each column, you are checking to see if the last row is selected, and inserting a new row for each column which is blank ("")...?
Remember, generally Java is zero indexed, this means, the last row is actually jTable1.getRowCount() - 1, so, it's unlikely that your if isRowSelected would be true, which is actually a good thing, cause otherwise you would have had a real mess...
Assuming I understand your question correctly (as it's a little vague), you could try something more like this...
boolean rowCompleted = true;
int lastRow = jTable1.getRowCount() - 1;
if (jTable1.isRowSelected(lastRow)) {
for (int col = 0; col < jTable1.getColumnCount(); col++) {
Object value = jTable.getValueAt(lastRow, col);
if (value == null || value.toString().trim().isEmpty()) {
rowCompleted = false;
break;
}
}
}
if (rowCompleted) {
// Insert new row...
} else {
// Show error message
}
Maybe use a TableModelListener.
Every time a cell is updated on the last row of the table you check to make sure all columns have data. If all columns have data you enable the "Add Row" button, otherwise you disenable the button.
I was checking this post and I used the code posted by MadProgrammer, but I made a few modifications and I got this working properly according to your need. If you want you can ask me for the project and I can happily provide it to you
private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
boolean rowCompleted;
int lastRow = jTable1.getRowCount()-1;
if(jTable1.isRowSelected(lastRow)){
for(int col=0;col<jTable1.getColumnCount();col++){
Object value = jTable1.getValueAt(lastRow, col);
if(value == null || value.toString().trim().isEmpty()){
rowCompleted=false;
}
else{
rowCompleted=true;
}
if(rowCompleted==true){
model.insertRow(jTable1.getRowCount(), new Object[]{});
}
else{
JOptionPane.showMessageDialog(null, "Something went worng. Try this:\n - Please select a row before adding new row.\n - Please verify there are no empty cells","Processing table's data",1);
}
break;
}
}
else{
JOptionPane.showMessageDialog(null, "Something went wrong. Verify this:\n - There is not any row selected.\n - You can only create new rows after last row","Processing table's data",1);
}
}
I hope this could help you, but first say thanks to MadProgrammer :D

How do I use use data from a Resultset in a JTable?

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;
}

Categories

Resources