I cant view data in JTable From a custom table model - java

Here is my code:
Object[][] refreshCartonCodesToTable = dbutils.checker.CartonCodesToTable();
String[] colnames = new String[6];
colnames[0] = selectCodes.invoiceTable.getColumnName(0).toString();
colnames[1] = selectCodes.invoiceTable.getColumnName(1).toString();
colnames[2] = selectCodes.invoiceTable.getColumnName(2).toString();
colnames[3] = selectCodes.invoiceTable.getColumnName(3).toString();
colnames[4] = selectCodes.invoiceTable.getColumnName(4).toString();
colnames[5] = selectCodes.invoiceTable.getColumnName(5).toString();
MyTableModel mod = new MyTableModel(refreshCartonCodesToTable, colnames);
selectCodes.invoiceTable = new JTable(mod);
selectCodes.invoiceTable.setVisible(true);
Custom model as shown below:
class MyTableModel extends DefaultTableModel {
public MyTableModel(Object data[][], Object columnames[]) {
super(data, columnames);
}
public Class getColumnClass(int col) {
if (col == 5) {
return Boolean.class;
} else {
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int col) {
if (col == 0) //first column will be uneditable
{
return false;
} else {
return true;
}
}
}
The table displays the columnames but the data is not diplayed. The array has data and the sample output is as shown below:
250VV 250VV0575W20140819 false B1 19 August 2014
250VV 250VV0561W20140819 false B1 19 August 2014
250VV 250VV0560W20140819 false B1 19 August 2014
250VV 250VV0559W20140819 false B1 19 August 2014
250VV 250VV0558W20140819 false B1 19 August 2014
There are six columns. The sixth column I want to place a checkbox in the cells.
Can somebody help me please.
Here is the source code for CartonCodesToTable();
public static Object[][] CartonCodesToTable() {
Object[][] array = null;
try {
dbutils.checker.connect_to_db_again_again();
sqlcommand = "SELECT Product_ID, carton_code, scanned, batchno,date FROM carton_codes where scanned ='false' order by bno asc";
rset = stmts.executeQuery(sqlcommand);
int row = 0;
while (rset.next()) {
rset.last();
row = rset.getRow();
}
array = new String[row][6];
rset.beforeFirst();
int x = 0;
while (rset.next()) {
array[x][0] = rset.getObject("Product_ID");
array[x][1] = rset.getObject("carton_code");
array[x][2] = rset.getObject("scanned");
array[x][3] = rset.getObject("batchno");
array[x][4] = rset.getObject("date");
array[x][5] = false;
x += 1;
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
return array;
}
When i use array[x][5] = false; i get an error 'java.lang.ArrayStoreException: java.lang.Boolean' So i decided to use array[x][5] = "false";

You haven't provided an MCVE like I suggested, so there's hard to tell what's going on. First thing I see though is poor use of the ResultSet you don't need to do all those things. For example your use of rs.last().
boolean last() throws SQLException - Moves the cursor to the last row in this ResultSet object.
About ResultSet from API
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable (See the API for an example how to do this)
So assuming you haven't make the ResultSet scrollable, that would explain you getting no results, as you have moved the cursor to the end with the call to rs.last()
That being said, you don't need to get the row count. Use a dynamic data structure to create the model instead. Just use a Vector. If you use an array for the data, DefaultTableModel will convert it to a Vector (under the hood) anyway.
A common approach is to make use of the ResultSetMetaData class and get the column count and create a Vector<Vector<Object>> dynamically and construct you DefaultTableModel that way. Something like:
public DefaultTableModel getModelFromResultSet(ResultSet rs) throws Exception {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
col[i - 1] = md.getColumnName(i);
}
Vector<Vector<Object>> dataVector = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = Vector<Object>();
for (int i = 1; i <= columnCount; i++) {
row.add(rs.getObject(i));
}
dataVector.add(row);
}
DefaultTableModel model = new DefaultTableModel(dataVector, cols) {
#Override
public Class<?> getColumnClass(int column) {
...
}
};
return model;
}
Or something like this. Haven't tested it (for any errors), but the basic concept is there.
As far as your ArrayStoreException, look at what you're doing
Object[][] array = null;
...
array = new String[row][6];
What's the point of doing this. You are making it every object has to be a String. Which may not be desirable for rendering.

Related

Unable to get column names as headers into JTable

I have this code that should create my JTable column hearders based on the field names returned from my query. For some reason my code is not working, I am very new to Java and I have been doing research but cant seem to find where my issue is. Any help will be greatly appreciated.
public void initTable(){
try {
DefaultTableModel tblModel = new DefaultTableModel()
{
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
};
tblMain.setModel(tblModel);
tblMain.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//tblMain.getTableHeader().setReorderingAllowed(false);
Connection dbconn = dbConn();
Statement stmt = dbconn.createStatement();
String qry = "SELECT * FROM Services";
ResultSet rs = stmt.executeQuery(qry);
int numCols = rs.getMetaData().getColumnCount();
System.out.println("Num Cols: " + numCols);
for (int col = 1; col <= numCols; col++){
tblModel.addColumn(rs.getMetaData().getColumnLabel(col));
//tblModel.addColumn("Tmp");
System.out.println(col + " - " + rs.getMetaData().getColumnLabel(col));
}
int row = 0;
while (rs != null && rs.next()){
tblModel.addRow(new Object[0]);
tblModel.setValueAt(rs.getString("ServiceID"), row, 0);
tblModel.setValueAt(rs.getString("Institution"), row, 1);
tblModel.setValueAt(rs.getString("Doctor"), row, 2);
tblModel.setValueAt(rs.getString("Street"), row, 3);
tblModel.setValueAt(rs.getString("City"), row, 4);
tblModel.setValueAt(rs.getString("State"), row, 5);
tblModel.setValueAt(rs.getString("ZipCode"), row, 6);
tblModel.setValueAt(rs.getDate("Date"), row, 7);
tblModel.setValueAt(rs.getDouble("Cost"), row, 8);
tblModel.setValueAt(rs.getInt("ServiceTypeID"), row, 9);
tblModel.setValueAt(rs.getString("Comments"), row, 10);
row++;
}
rs.close();
}
catch (Exception e){
e.printStackTrace();
}
}
Not really related to your problem but I would like to suggest a better way to add the data to the model.
Instead of creating an empty array and then using setValueAt(...) you can change the looping code to look something like:
while (rs != null && rs.next())
{
Vector<Object> row = new Vector<Object>(11);
tblModel.addRow(new Object[0]);
row.add(rs.getString("ServiceID"));
row.add(rs.getString("Institution"));
...
row.add(rs.getString("Comments"));
tblModel.addRow( row );
}
Reasons for this approach:
The DefaultTableModel stores its data in a Vector. So the data from the Array is copied to the Vector. Save resources by just using an Vector from the beginning.
The code is shorter to type. This also makes it easier to rearrange columns since you don't need to worry about indexes.
Every time you invoke the setValueAt(...) method an event is generated to tell the table to paint itself. So this is happening 12 times, once for the addrow() method and once for each setValueAt() method. By just using the addRow() method at the end you only generate one event.

ArrayIndexOutOfBoundsException error but I think the code is okay

So I have a function that populates JTable from my database.
I have here
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
if(isObjectInteger(rs.getObject(i)) && i>1) //checks if the value is Integer else not and is past the first column
{
System.out.println(i+"="+rs.getObject(i));
String label = columnNames.get(i); //THE ERROR IS ON THIS PART
newRow.addElement(getValue((Integer) rs.getObject(i),label)); //gets the value of specific foreign key id from another table
}
else
{
System.out.println(i+"="+rs.getObject(i));
newRow.addElement(rs.getObject(i));
} //inside row (new Rows)
}
rows.addElement(newRow); //outside row
}
return new DefaultTableModel(rows, columnNames)
{
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I have total 8 columns in my database the output of that System.out.println is:
The one's that get's inside the else:
1=1
2=test
3=A.
4=test
5=test
6=test
The one's that get's inside the if
7=1
8=23
As you can see the output is right but it always throws Array index out of range: 8 error on the String label = columnNames.get(i);
While ResultSet.getObject() requires an argument based on one, columnNames is a vector, with its indexes based on zero.
Hence valid values for it would be 0..7, not 1..8. In other words, the first part of your if statement should be:
System.out.println(i + "=" + rs.getObject(i));
String label = columnNames.get(i-1); // NOT "i".

Copy selected data from a jtable in frame1 to another table in frame2

I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
String sql = "select * from table1 where Bill_No like '"+jTextField2.getText()+"'";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
JFrame NewJFrame2 = new NewJFrame2();
NewJFrame2.setVisible(true);
int i=0;
while(rs.next()) {
Object bno = rs.getString("Bill No");
Object bamount = rs.getString("Bill Amount");
Object btds = rs.getString("TDS");
Object btax = rs.getString("Tax");
Object bpayable = rs.getString("Payable");
jTable1.getModel().setValueAt(bno,i, 0 );
jTable1.getModel().setValueAt(bamount, i, 1);
jTable1.getModel().setValueAt(btds, i, 2);
jTable1.getModel().setValueAt(btax, i, 3);
jTable1.getModel().setValueAt(bpayable, i, 4);
System.out.println(i);
i++;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Start by having a look at How to Use Tables.
If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.
You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.
The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like
TableModel original = table.getModel();
DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
for (int col = 0; col < original.getColumnCount(); col++) {
model.addColumn(original.getColumnName(col));
}
int[] selectedRows = table.getSelectedRows();
for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
int row = selectedRows[targetRow];
int modelRow = table.convertRowIndexToModel(row);
for (int col = 0; col < original.getColumnCount(); col++) {
model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
}
}
for example. Now you just need to pass model to the second window and apply it to the JTable contained within

Non Intersecting two ResultSet in Java

I have two result sets coming from two different database and I need to compare it. I want an operation like
A-B
to be performed on them.
I cannot perform row by row comparison as 1st row in A resultset can be present anywhere in B resultset.
Below is the code to do that in .NET, which is very easy and perfect .
var nonIntersecting = dtSource.AsEnumerable().Except
(
dtTarget.AsEnumerable(), DataRowComparer.Default
);
try
{
dtSrcToTgtResult = nonIntersecting.CopyToDataTable();
} catch (InvalidOperationException ex) {}
Here dtSource,dtTarget are datatables having source and target data from databases.
dtSrcToTgtResult contains data present in source but not in target, which is exactly what I want.
Can same be done in JavaScript with result sets. I can also check CachedRowSet or webRowSet if something like this is available in it.
EDIT
For people who are giving minus votes. this is what i already did, but its not solving the problem.
private Boolean compare(ResultSet rsSrc,ResultSet rsTgt,String ExecCondition)
{
Boolean status = true;
try
{
ResultSetMetaData metaSrc = rsSrc.getMetaData();
ResultSetMetaData metaTgt = rsTgt.getMetaData();
final int columnCountSrc = metaSrc.getColumnCount();
List<DBRow> dList = new ArrayList<DBRow>();
List<DBRow> DataInSourceNotInTarget = new ArrayList<DBRow>();
List<DBRow> DataInTargetNotInSource = new ArrayList<DBRow>();
DBRow d = new DBRow();
DBRow d1 = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
d.Row.add(metaSrc.getColumnName(column));
d1.Row.add(metaTgt.getColumnName(column));
}
DataInSourceNotInTarget.add(d);
DataInTargetNotInSource.add(d1);
if(ExecCondition.equals("Source To Target"))
{
while(rsSrc.next())
{
if(rsTgt.next())
{
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
Object valueTgt = rsTgt.getObject(column);
if(!valueSrc.toString().equals(valueTgt.toString()))
{
status=false;
System.out.println("ValueSRC: "+v alueSrc.toString());
System.out.println("ValueTgt: "+valueTgt.toString());
}
}
}
else
{
// if target rows ends
DBRow dr = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
dr.Row.add(valueSrc);
}
DataInSourceNotInTarget.add(dr);
}
}
}//exec condition if
if(ExecCondition.equals("Target To Source"))
{
while(rsTgt.next())
{
if(rsSrc.next())
{
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
Object valueTgt = rsTgt.getObject(column);
if(!valueSrc.toString().equals(valueTgt.toString()))
{
status=false;
System.out.println("ValueSRC: "+valueSrc.toString());
System.out.println("ValueTgt: "+valueTgt.toString());
}
}
}
else
{
// if Source rows ends
DBRow dr = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueTgt = rsTgt.getObject(column);
dr.Row.add(valueTgt);
}
DataInTargetNotInSource.add(dr);
}
}
for(DBRow obj:DataInTargetNotInSource)
{
obj.print();
}
}//exec condition if
}
catch(Exception e)
{
e.printStackTrace();
}
return status;
}
I have a solution that is functional but not optimal:
It requires to load all rows into in-memory data structures (each ResultSet is loaded into list, each item is map of column name-value)
loop on source rows' list and for every item in that list - search that it does not exist in target list (meaning o(n^2) processing)
I used Apache DbUtils to easily convert ResultSet to List.
import java.sql.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.dbutils.handlers.MapListHandler;
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// load source table
Statement st = conn.createStatement();
ResultSet sourceRs = st.executeQuery("SELECT * FROM source");
List<Map<String, Object>> sourceRows = new MapListHandler().handle(sourceRs);
sourceRs.close();
st.close();
// load target table
st = conn.createStatement();
ResultSet targetRs = st.executeQuery("SELECT * FROM target");
List<Map<String, Object>> targetRows = new MapListHandler().handle(targetRs);
targetRs.close();
st.close();
// for every row in source, look for no match in target
List<Map<String, Object>> diffRows =
sourceRows.stream()
.filter(sourceRow -> rowExistsInTable(sourceRow, targetRows) == false)
.collect(Collectors.toList());
diffRows.stream().forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
EDIT:
you will notice that the filtering of sourceRows is now done according to result of method rowExistsInTable(). I added methods to search row in table and check rows' equality without relying on java 8 lambda syntax (also added as much documentation as I could :))
/**
* checks if {#code searchRow} exists in {#code table}
* existence is determined according to {#code areRowsEqual} method
* #param searchRow {#code Map<String, Object>} where keys are column names and values are column vales
* #param table {#code List} of {#code Map<String, Object>} rows
* #return {#code true} if {#code searchRow} was found in {#code table}
*/
public static boolean rowExistsInTable(Map<String, Object> searchRow, List<Map<String, Object>> table)
{
for (Map<String, Object> tableRow : table) {
if (areRowsEqual(tableRow, searchRow)) return true;
}
return false;
}
/**
* checks if all of row1 columns are found with same values in row2
* note: does not check if there is column in row2 that does not exist in row1
* #param row1
* #param row2
* #return {#code true} if {#code row1} is equal to {#code row2}
*/
public static boolean areRowsEqual(Map<String, Object> row1, Map<String, Object> row2)
{
// loop on row1 columns
for (Map.Entry<String, Object> row1Column : row1.entrySet()) {
String row1ColumnName = row1Column.getKey();
Object row1ColumnValue = row1Column.getValue();
// search row1 column in row2
if (row2.containsKey(row1ColumnName) &&
row2.get(row1ColumnName) != null &&
row2.get(row1ColumnName).equals(row1ColumnValue)) {
// row1 column was found in row2, nothing to do
} else {
// row1 column was not found in row2
return false;
}
}
return true; // all row 1 columns found in row 2
}

ArrayList.size() returning incorrect value

I have a strange error which I can not get my head around where the .size() method does not appear to return the correct value.
This first bit of code creates the ArrayList.
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
try {
ResultSet rs = st.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
data.add(i, new ArrayList<String>());
}
int x = 0;
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(x).add(rs.getString(y + 1));
}
x++;
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
This is my TableModel class which is used to create the table when it's passed to it.
public class ResultTable extends AbstractTableModel {
private ArrayList<ArrayList<String>> data;
public ResultTable(ArrayList<ArrayList<String>> data) {
this.data = data;
}
public int getColumnCount() {
return data.get(0).size();
}
public int getRowCount() {
return data.size();
}
public Object getValueAt(int row, int col) {
return data.get(row).get(col);
}
}
Now the the problem is in the ResultTable class, now for a select query returning one row with 12 columns, the first data.get(0).size() call correctly returns 12, but the 2nd data.size() call incorrectly returns 12 also instead of 1, this is causing out of bounds errors, can anyone please explain this seemingly paradoxical result?
This is something you should've found easily when you debug your code...
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
data is an ArrayList of ArrayLists
try {
ResultSet rs = st.executeQuery(query);
A query returning 1 row of 12 columns
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
For each column in your recordset, being 12, you add an empty ArrayList in data
data.add(i, new ArrayList<String>());
}
resulting in data being an ArrayList of 12 empty Arraylists
This already explains why data.size() == 12
int x = 0;
while(rs.next()) {
for each record in your recordset, being 1
for(int y = 0; y < meta.getColumnCount(); y++) {
for each column in your recordset, being 12, you add a string to the ArrayList with the same index as the recordset
data.get(x).add(rs.getString(y + 1));
}
The first ArrayList in data (data.get(0)) will have 12 Strings
All other ArrayLists in data (data.get(x) where x > 0) will remain empty
x++;
}
Resulting in data being an ArrayList of 12 ArrayLists
of which only the first ArrayList has 12 Strings and the others are empty
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
When you create the data list, you create a sublist to hold the data for each column.
If that is what you want to do, you should add data from each column of the result set to the list that corresponds to it:
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(y).add(rs.getString(y + 1));
}
}

Categories