Here I want average of row5, row6, row7, then I want to check with another table whether calculation is right or wrong. How to achieve this?
for(WebElement rowElement:TotalRowCount)
{
List<WebElement> TotalColumnCount=rowElement.findElements(By.xpath("td/span"));
int ColumnIndex=1;
for(WebElement colElement:TotalColumnCount)
{
String s=colElement.getText().replace("%", "").replace(",","");
if(!s.isEmpty()&&!s.equals("NA"))
{
if(s.contains(".")||s.contains("-"))
{
double d=Double.parseDouble(s);
System.out.println("Row "+RowIndex+"Double value is"+d);
}
else
{
int x1=Integer.parseInt(s);
System.out.println("Row "+RowIndex+"Integer value"+x1);
}
ColumnIndex=ColumnIndex+1;
}
else{/*do nothing*/}
}
RowIndex=RowIndex+1;
}
Output:
Row 5Integer value140
Row 6Integer value51
Row 6Integer value52
Row 6Integer value51
Row 6Integer value36
Row 7Double value is30.0
Row 7Double value is30.65
Row 7Double value is29.38
Related
I am having trouble deleting the previous row of my second table of my Products Stock In GUI in Java.
The flow of the functionality of my GUI is this:
If the user will select a row in the first table of the GUI, the values of those rows will be reflected on the second rows
If the user will select another/different row in the first table, the previous reflected row which was selected in the first table must be deleted and is replaced by the current selected row.
To sum it up, I have to replace/delete the previous reflected rows if I will select a different row in the first table then replace that previous selected row into the current selected row.
Here's my source code:
private void firstTableMouseClicked(java.awt.event.MouseEvent evt) {
DefaultTableModel secondTblmodel = (DefaultTableModel) secondTable.getModel();
int selectPRoww = firstTable.getSelectedRow();
for (int x = 0; x < ProductAllData2[selectPRoww].length; x++) {
//ProductAllData2 is a 3D array
if (ProductAllData2[selectPRoww][x][0] != null) {
if (setRowCountID2 == 0)
secondTblmodel.setRowCount(0);
//Reflects and displays the values of the selected
// row from the first table to the second table
secondTblmodel.addRow(ProductAllData2[selectPRoww][x]);
// deletes previous row if index of selected row is
// greater than the previous selected row (doesn't work)
if (selectPRoww > selectPRoww) {
secondTblmodel.removeRow(selectPRoww - 1);
}
// deletes previous row if index of selected row is
// less than the previous selected row (doesn't work)
if (selectPRoww < selectPRoww) {
secondTblmodel.removeRow(selectPRoww + 1);
}
setRowCountID2++;
}
}
}
Am I missing something in my functionality or do I need to modify the for loops?
In my opinion, your logic should not be like this.
As the second table (View) depends on the selection of the first table, then the second table should always be cleared, then you do this logic.
//Reflects and displays the values of the selected
// row from the first table to the second table
secondTblmodel.addRow(data);
Important Point: Please use ListSelectionListener on table1, rather than depending on mouse clicks.
Example of usage:
table1.getSelectionModel().addListSelectionListener(new SharedListSelectionHandler());
class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
int firstIndex = e.getFirstIndex();
int lastIndex = e.getLastIndex();
boolean isAdjusting = e.getValueIsAdjusting();
output.append("Event for indexes "
+ firstIndex + " - " + lastIndex
+ "; isAdjusting is " + isAdjusting
+ "; selected indexes:");
if (lsm.isSelectionEmpty()) {
output.append(" <none>");
} else {
// Find out which indexes are selected.
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for (int i = minIndex; i <= maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
output.append(" " + i);
}
}
}
output.append(newline);
}
}
How to Write a List Selection Listener | The Java™ Tutorials
Similar StackOverflow: Deleting row from JTable after valueChanged event is triggered
In my code I am going through an XLSX-file row by row, validating them against a database with Apache POI 4.1.0. If I find a incorrect row I will "mark" them for deletion by adding it to the the List<XSSFRow> toRemove. After iterating over every row this small method is supposed to remove the rows marked for deletion:
ListIterator<XSSFRow> rowIterator = toRemove.listIterator(toRemove.size());
while (rowIterator.hasPrevious()) {
XSSFRow row = rowIterator.previous();
if (row != null && row.getSheet() == sheet) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
if (rowIndex == lastRowNum) {
sheet.removeRow(row);
} else if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.removeRow(row);
} else {
System.out.println("\u001B[31mERROR: Removal failed because row " + rowIndex + " is out of bounds\u001B[0m");
}
System.out.println("Row " + rowIndex + " successfully removed");
} else {
System.out.println("Row skipped in removal because it was null already");
}
}
But for some unknown reason it removes all rows perfectly and then throws a XmlValueDisconnectedException when getting the row index (getRowNum()) of the last (first added) row.
Relevant part of the Stacktrace:
org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:400)
at Overview.removeRows(Overview.java:122)
EDIT: I also tried changing the iteration process (see below) but the error stays the same.
for (XSSFRow row : toRemove) {
// same code as above without iterator and while
}
The error occurs if one row is double contained in List toRemove. A List allows duplicate entries. So the same row may be double added to the List. If then Iterator gets the first occurrence of that row and this will be removed properly from the sheet. But then if the same row occurs again later, the row.getRowNum() fails that way because the row does not more exists in the sheet.
Here is complete code to reproduce that behavior:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
public class ExcelRemoveRows {
public static void main(String[] args) throws Exception {
String filePath = "Excel.xlsx"; // must contain at least 5 filled rows
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
Sheet sheet = workbook.getSheetAt(0);
List<Row> toRemoveList = new ArrayList<Row>();
toRemoveList.add(sheet.getRow(0));
toRemoveList.add(sheet.getRow(2));
toRemoveList.add(sheet.getRow(4));
toRemoveList.add(sheet.getRow(2)); // this produces the error
System.out.println(toRemoveList); // contains row hawing index 2 (r="3") two times
for (Row row : toRemoveList) {
System.out.println(row.getRowNum()); // XmlValueDisconnectedException on second occurance of row index 2
sheet.removeRow(row);
}
FileOutputStream out = new FileOutputStream("Changed"+filePath);
workbook.write(out);
out.close();
workbook.close();
}
}
The solution is to avoid that the List contains the same row multiple times.
I would not collecting the rows to remove in a List<XSSFRow> but the row numbers to remove in a Set<Integer>. That would avoid duplicates since a Set does not allow duplicate elements. The row to remove then can simply got via sheet.getRow(rowNum).
Code:
...
Set<Integer> toRemoveSet = new HashSet<Integer>();
toRemoveSet.add(sheet.getRow(0).getRowNum());
toRemoveSet.add(sheet.getRow(2).getRowNum());
toRemoveSet.add(sheet.getRow(4).getRowNum());
toRemoveSet.add(sheet.getRow(2).getRowNum());
System.out.println(toRemoveSet); // does not contain the row index 2 two times
for (Integer rowNum : toRemoveSet) {
Row row = sheet.getRow(rowNum);
System.out.println(row.getRowNum());
sheet.removeRow(row);
}
...
This question already has an answer here:
JTable Java Error Stack OverFlow when setvalue to a specific column
(1 answer)
Closed 6 years ago.
I am getting stackoverflow error when I try to change one of columns data when 2 columns of the columns has been edited.
I have 3 columns which are items, quantity, price.
I want to calculate the price when items and quantity has an input. Below is my code:-
itemsTable.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
for (int i = 0; i < itemsTable.getRowCount(); i++) {
if (itemsTable.getValueAt(i, 0) != null) {
String item = itemsTable.getValueAt(i, 0).toString();
double price = Double.parseDouble(selectedItem.substring(item.indexOf("RM") + 2, item.length())); //get price from the cell
double qty = Double.parseDouble(itemsTable.getValueAt(i, 1).toString()); //get quantity from cell
itemsTable.setValueAt(price * qty, i, 2); //calculate price * qty and set price
}
}
}
});
I set a combobox that loaded with database data to items column and a JSpinner for quantity
What am I doing wrong? I am new to JTable.
EDIT
Answer:(credits to Titus)
#Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE && e.getColumn() != 2) {
for (int i = 0; i < itemsTable.getRowCount(); i++) {
if (itemsTable.getValueAt(i, 0) != null) {
...
}
}
}
}
Also wouldn't hurt to limit the loop to going from row e.getFirstRow() thru e.getLastRow(), and maybe updating price in an invokeLater process as well. But titus hit it head on: gotta stop the infinite cascade of change invokes handler which makes change that invokes handler which makes change...
I am looking to get the value of the selected row in an AbstractTableModel and I am noticing some things. It is correctly reporting what sell (row) I am on, when it is selected, but as soon as I click my button to remove, the selected row value goes to 0. Resulting in the 0 row always being removed. I want to get the value int selectedRow and use it to remove it from the table and my ArrayLists.
ListSelectionModel rsm = table.getSelectionModel();
ListSelectionModel csm = table.getColumnModel().getSelectionModel();
csm.addListSelectionListener(new SelectionDebugger(columnCounter,csm));
columnCounter = new JLabel("(Selected Column Indices Go Here)");
columnCounter.setBounds(133, 62, 214, 14);
csm.addListSelectionListener(new SelectionDebugger(columnCounter,csm));
contentPane1.add(columnCounter);
rowCounter = new JLabel("(Selected Column Indices Go Here)");
rowCounter.setBounds(133, 36, 214, 14);
rsm.addListSelectionListener(new SelectionDebugger(rowCounter, rsm));
contentPane1.add(rowCounter);
SelectionDebugger:
public class SelectionDebugger implements ListSelectionListener {
JLabel debugger;
ListSelectionModel model;
public SelectionDebugger(JLabel target, ListSelectionModel lsm) {
debugger = target;
model = lsm;
}
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
// skip all the intermediate events . . .
StringBuffer buf = new StringBuffer();
int[] selection = getSelectedIndices(model.getMinSelectionIndex(),
model.getMaxSelectionIndex());
if (selection.length == 0) {
buf.append("none");
//selectedRow = buf.toString();
}
else {
for (int i = 0; i < selection.length -1; i++) {
buf.append(selection[i]);
buf.append(", ");
}
buf.append(selection[selection.length - 1]);
}
debugger.setText(buf.toString());
System.out.println("CampaignConfiguration: Selected Row: " + selection[selection.length - 1]);
// Set the selected row for removal;
selectedRow = selection[selection.length - 1];
}
}
// This method returns an array of selected indices. It's guaranteed to
// return a nonnull value.
protected int[] getSelectedIndices(int start, int stop) {
if ((start == -1) || (stop == -1)) {
// no selection, so return an empty array
return new int[0];
}
int guesses[] = new int[stop - start + 1];
int index = 0;
// manually walk through these . . .
for (int i = start; i <= stop; i++) {
if (model.isSelectedIndex(i)) {
guesses[index++] = i;
}
}
// ok, pare down the guess array to the real thing
int realthing[] = new int[index];
System.arraycopy(guesses, 0, realthing, 0, index);
return realthing;
}
}
}
The TableModel has nothing to do with selection. The View(JTable) is responsible for the selection.
I want to get the value int selectedRow and use it to remove it from the table and my ArrayLists.
You should NOT have separate ArrayLists. The data should only be contained in the TableModel.
If you want to delete a row from the table (and the TableModel) then you can use the getSelectedIndex() method of the table in your ActionListener added to the "Delete" button. Something like:
int row = table.getSelectedIndex();
if (row != -1)
{
int modelRow = table.convertRowIndexToModel( row );
tableModel.removeRow( modelRow );
}
If you are not using the DefaultTableModel, then your custom TableModel will need to implement the "removeRow(...)" method.
i create JTable in that table value are retrieve from data base
(Except fifth column) in fifth column .i enter value through keyboard
in fifth column but when getting value again from jtable at that time
i am not getting last entered value in fifth column please suggest
something
my method code bellow
public class TableDataDelete implements ActionListener
{
public void actionPerformed(ActionEvent ee) {
int b = table.getRowCount();
System.out.println("row count" + b);
for (int i = 0; i <b; i++) {
try
{
String str = (String) table.getModel().getValueAt(i, 3);
String str1 = (String) table.getModel().getValueAt(i, 5);
if (!(str1 == null)) {
((DefaultTableModel)table.getModel()).removeRow(i);
table.repaint();
System.out.println("remove row no is"+i);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception"+e);
}
}
}
}
working code when i enter value of five cells it can get only first four cell from the column cant getting last entered cell value
You should use this code to stop cell editing to get last value
if(table.getCellEditor() != null){
table.getCellEditor().stopCellEditing();
}