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));
}
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'm confused that why jTextField, TOTALAMOUNT , is showing nothing for the following code, why ?
public double SUM(){
int rowcount = BILL_INFO_TABLE.getRowCount();
double sum=0;
for(int i=0;i<rowcount;i++){
sum = sum + Double.parseDouble(BILL_INFO_TABLE.getValueAt(i, 4).toString());
}
return sum;
}
private void BILL_DETAILSMouseClicked(java.awt.event.MouseEvent evt)
{
DefaultTableModel model=(DefaultTableModel)this.BILL_DETAILS.getModel();
int i = BILL_DETAILS.getSelectedRow();
if(i==-1){
JOptionPane.showMessageDialog(this,"SELECCION !!");
}else{
DATA_TABLE2();
TOTALAMOUNT.setText(Double.toString(SUM()));
}
}
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));
}
}
I am facing a problem with the functionality of removing a row(s) form one table view to another table view currently I have two button one add row form the bottom table to the above and the next add from the above the the botton. the button that add from bottom to top called add and the button that add from top to bottom called remove in both once the row is copied across it get deleted from the original table.
The problem I am facing is:
when I add all the row from the bottom table to the top table
if I sort Column 0 in top table ,then try to remove the row from the top table to the bottom table
the row do not get deleted from the top table although it is added in the bottom table.
Could you please Help me solve this problem or advice me on a better way?
Here is my current code:
Remove button:
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
spTable.removeAll();
x = resultTable.getSelectedRows();
String[] cName= {"Column 0","Column 1","Column 2","Column 3","Column 4","Column 5","Column 6","Column 7","Column 8"};
if(rTable.getRowCount()==0){
model=addToNew(resultTable,x,cName,model);
}else{ model =addToExisting(resultTable,rTable, x, model);
}
deletRows(x,resultTable);
rTable.setModel(model);
JScrollPane spS = new JScrollPane(rTable);
rTable.getColumnModel().getColumn(1).setPreferredWidth(290);
spS.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spS.setPreferredSize(new Dimension(800,200));
rTable.setFillsViewportHeight(true);
spTable.add(spS);
validate();
}});
Add button:
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.removeAll();
x = rTable.getSelectedRows();
String[] cName= {"Column 0","Column 1","Column 2","Column 3","Column 4","Column 5","Column 6","Column 7","Column 8"};
if(resultTable.getRowCount()==0){
model=addToNew(rTable,x,cName,model);
}else{ model =addToExisting(rTable,resultTable, x, model);
}
deletRows(x,rTable);
resultTable.setModel(model);
JScrollPane spS = new JScrollPane(resultTable);
resultTable.getColumnModel().getColumn(1).setPreferredWidth(290);
spS.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spS.setPreferredSize(new Dimension(800,170));
panel.add(spS);
resultTable.setFillsViewportHeight(true);
validate();}});
deletRow
public void deletRows(int[] selected, JTable t){
for(int i = selected.length-1;i>=0;i--){
int y = selected[i];
((DefaultTableModel)t.getModel()).removeRow(y);
validate();}}
/**
* this method allow to add rows to an New table
*/
public DefaultTableModel addToNew(JTable t1,int[] selected,String[] ColName, DefaultTableModel m){
String[] name = ColName;
int col = name.length;
m =new DefaultTableModel();
for(int i= 0;i<col;i++){
m.addColumn(name[i]);
}
Object[] data= new Object[col];
for(int i =0; i<selected.length;i++){
int y= selected[i];
for (int z =0; z<col;z++){
if( t1.getValueAt(y, z)!= null){
String value = t1.getValueAt(y, z).toString();
data[z]= value;
}else{
data[z]=null;
}
}
m.addRow(data);
}
return m;
}
/* this method allow to add rows to an Existing table */
public DefaultTableModel addToExisting(JTable t1,JTable t2, int[] selected, DefaultTableModel m){
m =(DefaultTableModel)t2.getModel();
Object[] data= new Object[m.getColumnCount()];
for(int i =0; i<selected.length;i++){
int y= selected[i];
for (int z =0; z<m.getColumnCount();z++){
if( t1.getValueAt(y, z)!= null){
String value = t1.getValueAt(y, z).toString();
data[z]= value;
}else{
data[z]=null;
}
}
m.addRow(data);
}
return m;
}
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;
}