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".
Related
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String dishName = "";
ArrayList<Integer> st = new ArrayList<Integer>();
int rowCount = table.getRowCount();
int fPrice;
int rowIndex = 0;
int colIndex = 4;
boolean emptyFlag = false;
do {
String price = (String) table.getValueAt(rowIndex, 4);
fPrice = Integer.parseInt(price);
if (price != null && price.length() != 0) {
st.add(fPrice);
rowIndex++;
} else {
emptyFlag = true;
}
} while (rowIndex < rowCount && !emptyFlag);
Collections.sort(st);
int key = Integer.parseInt(searchPrice.getText());
int low = 0;
int high = st.size() - 1;
int searchResult = MenuInfo.priceSearch(st, low, high, key);
if(searchResult==-1){
JOptionPane.showMessageDialog(this, "Could not find the dish of your price!");}
else{
dishName = (String) table.getValueAt(searchResult,1);
JOptionPane.showMessageDialog(this, "The price you have searched can afford " + dishName);
}
} //ends here
The above code is the code I have tried in my program. But it can display the corresponding dishName only if the data are sorted previously. If I add dish of lower price, then it displays the dishname of first row. Please do appreciate my request :)
Here is the image of my jtable
I wrote some code that may help. It looks like you're using Swing, so I used Swing. My code will find the corresponding value, but not sort the rows. I'll share it, but if you really need it to be sorted, let me know.
public static void main(String[] args) {
String[] headers = {"Name","Number"};
String[][] rowData = {{"foo","500"},{"bar","700"}};
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//frame.add(panel);
//A table is controlled by its model, so we need a variable to access the model
DefaultTableModel model = new DefaultTableModel(rowData,headers);
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
//To allow sorting, we us a TableRowSorter object
TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
table.setRowSorter(sorter);
//We have to set the 2nd column to be sortable
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
//sorting on 2nd column (with index of 1), which is Number
sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
//add new value, then sort
Object[] newRow = {"baz", "600"};
model.addRow(newRow);
sorter.sort();
panel.add(scroll);
frame.add(panel);
frame.setSize(800, 400);
//show is deprecrated.. I shouldn't be using it!
frame.show();
int minIndex = findMin(table, 1);
//use the row index of the min item in column 1 to get the corresponding value in column 0
System.out.println("Minimum String: " + table.getValueAt(minIndex, 0));
}
//find min value in the column with index tableColumnIndex and return the row index of that item
public static int findMin(JTable table, int tableColumnIndex) {
int minIndex = 0;
String min = table.getValueAt(0, tableColumnIndex).toString();
for (int i = 1; i < table.getRowCount(); i++) {
if (table.getValueAt(i, tableColumnIndex).toString().compareTo(min) < 0) {
min = table.getValueAt(i, tableColumnIndex).toString();
minIndex = i;
}
}
return minIndex;
}
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
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.
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));
}
}
How to get row with index i froj JTable ? I looked at member functions but there is nothing like getRowAt . Can anybody help ?
There is no "row" object for a table, so nothing you could get with a getRow method.
You can ask getValueAt() to get the individual values, use it for each column and you have your complete row.
AFAIK, there is no such method. Write something like that:
public String[] getRowAt(int row) {
String[] result = new String[colNumber];
for (int i = 0; i < colNumber; i++) {
result[i] = table.getModel().getValueAt(row, col);
}
return result;
}
P.S - Use table.getValueAt() if you want to respect a rearranged by the user column order.
I recommend to create a TableModel based on a list of POJOs.
It's then easy to add a method like:
MyPojo getData(int index);
Have a look at this sample I wrote some time ago for a starting point:
http://puces-samples.svn.sourceforge.net/viewvc/puces-samples/tags/sessionstate-1.0/sessionstate-suite/sessionstate-sample/src/blogspot/puce/sessionstate/sample/ParticipantTableModel.java?revision=13&view=markup
Try something like this
private void getIndexRow(){
int i;
int row = 0;
int column = 0;
i=Integer.parseInt(myTable.getValueAt(row,column).toString());
}
Another way of doing it is using the table model's getDataVector() method.
DefaultTableModel tm = (DefaultTableModel) table.getModel();
Vector<Object> rowData = tm.getDataVector().elementAt(rowIndex);
private void jTable1MousePressed(java.awt.event.MouseEvent evt) {
int selectedRow;
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
selectedRow = lsm.getMinSelectionIndex();
int numCols = jTable1.getColumnCount();
model = (DefaultTableModel) jTable1.getModel();
System.out.print(" \n row " + selectedRow + ":");
for (int j = 0; j < numCols; j++)
{
System.out.print(" " + model.getValueAt(selectedRow, j));
}
}
});
}
Using this you can get value of whole row where u click on particular row.
This function is working well for me.
private Object[] getRowAt(int row, DefaultTableModel model) {
Object[] result = new Object[model.getColumnCount()];
for (int i = 0; i < model.getColumnCount(); i++) {
result[i] = model.getValueAt(row, i);
}
return result;
}