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;
}
Related
guys, my question is about jtable column values, I am stuck on a problem. I want to sum jtable column values and put it into the text field. I am inserting values into jtable and if a row is empty, it is not calculating the total afterward. I couldn't understand what is the problem. I created a method and call it on button event.
public void getSum(){
int total=0;
for(int i=0; i<JV_tbl.getRowCount(); i++){
int amount = Integer.parseInt((String) JV_tbl.getValueAt(i, 6));
total+=amount;
}
JV_totalDebit_box.setText(String.valueOf(total));
}
and the button event code.
private void btn_entrySaveActionPerformed(java.awt.event.ActionEvent evt) {
model = (DefaultTableModel)JV_tbl.getModel();
model.addRow(new Object[]{
jv_no_box.getText(),
JV_entry_box.getText(),
((JTextField)date_txt.getDateEditor().getUiComponent()).getText(),
JV_Acc_code.getText(),
JV_acc_title.getText(),
JV_desc_box.getText(),
JV_debit_box.getText(),
JV_credit_box.getText(),
prep_box.getText(),
checked_box.getText(),
approved_box.getText()
});
getSum();
}
Change your getSum() function as below. It will remove all the blank rows and will continue the total afterward.
public void getSum(){
int rowcount1 = JV_tbl.getRowCount();
DefaultTableModel tbm1 = (DefaultTableModel) JV_tbl.getModel();
for(int i = rowcount1-1; i >=0; i--){
if(JV_tbl.getValueAt(i, 6) == null){
tbm1.removeRow(i);
}
}
int total=0;
for(int i=0; i<JV_tbl.getRowCount(); i++){
int amount = Integer.parseInt(JV_tbl.getValueAt(i, 6).toString());
total+=amount;
}
JV_totalDebit_box.setText(String.valueOf(total));
}
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.
All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.
private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");
private DefaultTableModel model = new DefaultTableModel(){
#Override
public Class<?> getColumnClass(int column){
if ((column & 1) != 0 ){
return ImageIcon.class;
}else{
return String.class;
}
}
};
initTables();
JTable table = new JTable();
table.setModel(model);
private void initTables(){
model.addRow(new Object[]{});
int rowsToAdd = 0;
int rowCount = 0;
int columnId = 0;
for(HouseObject aHouse : houses){
for(RoomObject aRoom : aHouse.getRooms()){
model.addColumn(null);
model.addColumn(aRoom.getId());
model.setValueAt(aRoom.getId(), 0, columnId);
if (rowCount < aRoom.getEvents().size()){
rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
for(int i = 0; i <= rowsToAdd; i++){
model.addRow(new Object[]{});
}
rowCount = model.getRowCount();
}
for(int i = 0; i < aRoom.getEvents().size(); i++){
model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);
for(String houseDone : housesDone){
if(aRoom.getEvents().get(i).getId().contains(houseDone)){
model.setValueAt(doneImage , i+1, columnId+1); // this does not work
}else{
model.setValueAt(notDoneImage, i+1, columnId+1);
}
}
}
columnId = columnId+2;
}
}
}
You need to install renderer for your table
Here is the renderer:
public class IconTableCellRenderer extends DefaultTableCellRenderer {
#Override
protected void setValue(Object value) {
if (value instanceof Icon) {
setText(null);
setIcon((Icon) value);
} else {
super.setValue(value);
}
}
}
And so you must install it:
JTable table = new JTable();
table.setModel(model);
table.setDefaultRenderer(ImageIcon.class, new IconTableCellRenderer());
I have a JTable which I create dynamically from List objects.
Well you can't just add Strings to the table since then image will need to be added as an ImageIcon. So you would need a List so you can add String and Icon values.
Then you need to override the getColumnClass(...) method of your TableModel to return Icon.class for the column that contains the Icon. The table will then use the appropriate renderer for the Icon.
See: How to set icon in a column of JTable? for a working example.
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".
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
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));
}
}