retrieve boolean values from jtable - java

in my Jtable I have a column with boolean values displayed as checkbox.
I can retrive the value cell only when the value is true, when values i false I can't read the values.
I write my code:
int row = jTMezziInt.getRowCount();
int h=0;
while (h<=row){
chk= ((Boolean)jTMezziInt.getValueAt(h, 6)).booleanValue();
//if chk is true I can read;
// if chk is false the execution stopped at the chk assignement;
if (chk)
((DefaultTableModel )this.jTMezziInt.getModel()).removeRow(h);
row = jTMezziInt.getRowCount();
h=h+1;
}
TableColumn Selez = jTMezziInt.getColumnModel().getColumn(6);
}
For define the table I had used netbeas with table editor.
Thanks everybody for help;

There are one of two possible issues here from what I can see. The most likely issue is that you start with h = 0 and then end with h = row (since your while loop iterates while h <= row).
Say for example you have 3 rows in your table. This loop will now run for h = 0, h = 1, h = 2 and h = 3, i.e. it runs 4 times but you only have 3 rows (indexed 0, 1 and 2 there is no row with index 3). This would cause a null pointer exception on its final iteration. Is this the behaviour you are seeing?
To sort it out just make your while loop condition h < row, not h <= row. If this does not work then let me know and we can discuss the other possible issue.
Another issue is that you still increment h even if the row you are checking is deleted. If we are checking row 1 and then delete row 1 then row 2 will become row 1, so we need to recheck this new row 1. So you should only increment h if the current row you are checking is not deleted.
Finally, as an aside, note that if you are using one of the later JDKs there is no need to call booleanValue() (this is called unnecessary unboxing). This will be done automtically for you. So you can change the following:
chk= ((Boolean)jTMezziInt.getValueAt(h, 6)).booleanValue();
to:
chk= (Boolean)jTMezziInt.getValueAt(h, 6);
It's just neater and better style.

Related

How to get a row count for a table that does not display all rows at once?

I have a table that when the page is fully displayed has a row count of 20 rows. However, if there is more than 20, and the user scrolls down additional rows are added. Since it only gets the initial row count, I can never find the element I'm trying to search for.
What I have right now is something along these lines.
boolean isFound = false;
List<WebElement> rowList = webdriver.findElements(By.xpath("//*[contains(#class, 'requestRow')]"));
int rowCount = rowList.size();
String rowNum = null;
for (int i = 1; i <=rowCount+1; i++){
rowNum = Integer.toString(i);
}
Any idea of how I can have the table expanded and capture the new value?
OK, so what I did was create a list based on the current row count.
I then loop through the list incrementing one each time. If the number I'm looking for is found in the table, it does what I need doing. If it gets to a number higher than the current count of rows, I click the load more button, add the new value to my row count, and keep searching.

divide excel sheet based on spesific cell values

i have a data sheet in excel about 950000 row with 7 col.and i want to divide it based on V5 col data. V5 holds data for time in seconds into one hour so i need to divide the data into sheets each sheet contains all value related to one minute and so on until finish splitting
if any help in do it with micro VBA thats will be good.
this is what i could do in VBA
Sub SPLIT()
Dim ws1, ws2 As Worksheet
Dim row2 As Integer
Dim rw As Range
Dim dv, fv As Variant
Set ws1 = Sheets("sheet1")
Set ws2 = Sheets.Add
row2 = 1
For Each rw In ws1.Rows
If rw.Cells(1, 5).Value2 = 00:00:59 Then " and so on until i divide each minute data rows alone"
Exit For
End If
So I've put something together for you that will get you started. You'll likely have to adjust the code for the exact time bounds that fit your requirement (which will be a good learning oppurtunity!). Note that you can take an approach of setting these bounds as either fixed or variable (i.e.: increments of minutes/seconds/hours, or the fixed bounds I have now)
To set this up you'll need three sheets in your workpaper named (1) Hours, (2) Minutes, and (3) Seconds.
As the code is set up the rows get sorted and placed into bounds depending on if it's under one minute, under one hour, or greater than one hour.
Take a stab at adjusting the code to your exact requirements and if you have any questions feel free to let me know!
Function Last_Row(Sheet_Name As String)
Last_Row = Sheets(Sheet_Name).Range("A" & Sheets(Sheet_Name).Rows.Count).End(xlUp).Row
End Function
Sub AllocateSheet()
Dim Cell As Variant
Dim Cell_Range As Range
Set Cell_Range = Range("E2:E990000")
Seperator_Second = TimeValue("00:00:01")
Seperator_Minute = TimeValue("00:01:00")
Seperator_Hour = TimeValue("01:00:00")
For Each Cell In Cell_Range
If Cell.Value >= Seperator_Hour Then
Rows(Cell.Row).Copy Destination:=Sheets("Hours").Rows(Last_Row("Hours") + 1)
ElseIf Cell.Value <= Seperator_Hour And Cell.Value >= Seperator_Minute Then
Rows(Cell.Row).Copy Destination:=Sheets("Minutes").Rows(Last_Row("Minutes") + 1)
ElseIf Cell.Value <= Seperator_Minute And Cell.Value >= Seperator_Second Then
Rows(Cell.Row).Copy Destination:=Sheets("Seconds").Rows(Last_Row("Seconds") + 1)
End If
Next Cell
End Sub
I reach into deviding minutes uisng this code any help in edit this code so i can divide the total rows in the sheet about 1000000 row also the code make the loop only to 60000 row in E colunm. I dont know why it just took from 1 to 6000 E1:E6000 and make a loop on 60000 row any help. also how i can craete new sheet to
paste to it inside code.
Option Explicit
Sub Test()
ti=TimeValue("00:00:00")
Dim Cell As Range
With Sheets(1)
For Each Cell In .Range("E1:E6000" & .Cells(.Rows.Count, "E").End(xlUp).Row)
If Cell.Value <= ti Then
.Rows(Cell.Row).Copy Destination:=Sheets("first minute").Rows(Cell.Row)
End If
Next Cell
End With
End Sub

Optimization of deletion nodes in 2-d array

I have double dimensional array of dimensions 720x90. Let's denote rows by R and C as columns.
R1 = {C1,...,C90}
....
R720 = {C1,...C90}
Now, I want to see if any of the data in any of the rows appears anywhere else in any other rows. For instance, lets say the data in row 470 and column 67 is a duplicate of row 672 and column 34. In that case, I want to remove both row 470 and row 672 from the data set and continue checking. After I have checked all the rows, I want to print just the index of the rows that have survived. I have written a brute-force method of this. However, when I run this code, it never returns and I am not able to diagnose why. Also, is there a more efficient way to do this?
//check all the subsets of the interleaved data
public static int checkSubsets(String[][] subsets){
List subset = new ArrayList();
for(int i = 0; i< 720; i++){
for(int j = 0; j < 90; j++)
subset.add(subsets[i][j]);
}
Object duplicate;
Iterator itr = subset.iterator();
while(itr.hasNext()){
duplicate = itr.next();
while(itr.hasNext()){
subset.remove(duplicate);
itr=subset.iterator(); //to avoid concurrent modification
itr.next();
}
}
return subset.size();
}
Clarifications: Lets say I am iterating through looking at each value in the matrix. I take the first value in R1 C1 (row 1 - column 1). I find that these values are found somewhere in the 12, 346,123, 356 row. Then I remove all those rows from the matrix. So now the matrix is 5 rows smaller. I stop checking row 1 now and move onto row 2. I continue checking, skipping over row 12, 346, 123, and 356. Hence, I am after a row that is unique (has 90 values that are all unique).
I am not sure what the code you wrote has to do with the requirement, I will give you the approach of the answer yet you have to try it yourself first.
it is clear that you need to iterate on each row to check for possible duplicates yet this will cause a performance failure , you can overcome this with a smiple use of HashMap, first store each entry in the map , the key will be the value of the node of the array, and the value should be the coordinates of this node.
When iterating over the array for each row you should find the y coordinates from the map which is common between all nodes of the row, so duplicate rows detected.
In order to avoid keep checking the already removed rows try to store all the rows to be deleted and remove them once you are done, you can use Set to store them to avoid duplicate.
Good luck with the implemenation.
The algorithm is almost there, but helpfull data-structures are missing.
To add a bit of spice I used Java 8 somewhat.
As you did one can collect the values to check for duplicates.
However one needs to remember the first row of that value, as only there it is still unknown whether a duplicate exists.
public static int checkSubsets(String[][] subsets) {
// The results.
final Set<Integer> duplicateRows = new HashSet<>();
// From the first occurrence of a duplicate value we do not know it yet,
// so need to remember.
final Map<String, Integer> firstRowOfValue = new HashMap<>();
for (int i = 0; i < subsets.length; ++i) {
for (int j = 0; j < subsets[i].length; ++j) {
final String value = subsets[i][j];
Integer oldRow = firstRowOfValue.putIfAbsent(value, i);
if (oldRow != null) { // Duplicates
duplicateRows.add(i);
duplicateRows.add(oldRow);
// oldRow might already be added if third duplicate or same row.
}
}
}
IntStream.rangeOf(0, subsets.length)
.filter(i -> !duplicateRows.contains(i))
.forEach(System.out::println);
return subsets.length - duplicateRows.size();
}
The IntStream part would be in java 7:
for (int i = 0; i < subsets.length; ++i) {
if (!duplicateRows.contains(i)) {
System.out.println(i);
}
}
With java 7 you can safely substitute here putIfAbsent with put.

Calculating total value in JTable Column using new value

I want to calculate total value in index [0][2], previous value is 0, but I have replaced and display it with the calculation result “1/y”, and when I calculate total value, value that summed is previous value that containing “0”, this my code,
//observation table
//0 1 2 3 4 5 6
titleColumn = new Object[]{"Time (Second)","Medicine", "1/y","x2", "X/Y", "Y^", "Error"};
//0 1 2 3 4 5 6
allData = new Double[][] {{1.0,1.02,0.0,0.0,0.0,0.0,0.0},
{2.0,0.667,0.0,0.0,0.0,0.0,0.0},
{3.0,0.367,0.0,0.0,0.0,0.0,0.0},
{4.0,0.278,0.0,0.0,0.0,0.0,0.0},
{5.0,0.237,0.0,0.0,0.0,0.0,0.0},
{6.0,0.187,0.0,0.0,0.0,0.0,0.0},
{7.0,0.155,0.0,0.0,0.0,0.0,0.0},
{8.0,0.156,0.0,0.0,0.0,0.0,0.0},
{9.0,0.142,0.0,0.0,0.0,0.0,0.0},
{10.0,0.111,0.0,0.0,0.0,0.0,0.0},
{11.0,0.12,0.0,0.0,0.0,0.0,0.0},
{12.0,0.097,0.0,0.0,0.0,0.0,0.0},
{13.0,0.099,0.0,0.0,0.0,0.0,0.0},
{14.0,0.089,0.0,0.0,0.0,0.0,0.0},
{15.0,0.079,0.0,0.0,0.0,0.0,0.0},
{0.0,0.0,0.0,0.0,0.0,0.0,0.0}};
tableModelObservation = new DefaultTableModel(allData, titleColumn);
tableObservation.setModel(tableModelObservation);
int row,column,inputRow,inputColumn;
//index [0][2] was replaced with calculation 1/y
row = 0;
column = 1;
inputRow = 0;
inputColumn = 2;
double onePerY = 0;
for(int a=0;a<allData.length;a++){
onePerY = 1/allData[row][column];
//is this the way to use getValueAt() and for indicating that the dependent cell has been change ?
tableObservation.getModel().getValueAt(row, column);
tableObservation.firePropertyChange("1/y", inputRow, inputColumn);
tableObservation.getModel().setValueAt(onePerY, inputRow, inputColumn);
inputRow++;
row++;
}
//calculation total 1/y, summing is still using previous value "0"
row = 0;
column = 2;
inputRow = 15;
inputColumn = 2;
double totalOnePerY = 0;
for (int a=0;a<allData.length;a++){
totalOnePerY += allData[row][column];
row++;
}
//displaying result in row index[15] and column index[2]
tableObservation.getModel().setValueAt(totalOnePerY, inputRow, inputColumn);
this column values ”1/y” after calculation process
What should I do, to be able to summing it using new value ?
all the assistance that you gave, I would appreciate it, thank you
As shown in DependentColumn, you can calculate derived values in your implementation of getValueAt(). If a column on which the value depends is editable, be sure to fire an event indicating that the dependent cell has changed.
Addendum: I’ve added my code with getValueAt(), but the result is the same.
Absent your sscce I'm guessing: I see that you access the allData array after you use it to construct and update the DefaultTableModel. I'm not sure about the goal of the exercise, but you probably wan't to update the array before doing so. DefaultTableModel uses Vector internally, and it ignores the array after construction completes.
You can try to use EnvelopeTableMode which wraps original model and can provide grouping functions (SUM, COUNT, AVG...).

Reusing of components in Java not properly trimming un-reused ones

I have a javax.swing.JPanel called calcResPanel (using a java.awt.GridLayout with 1 column and indefinite (0) rows) which is to receive and display a set of BHSelectableLabels (which extend javax.swing.JTextField) with collectively represent the text stored in the list of Strings called results. I figured that I might as well give it the following behavior:
The first time, it will only add new ones
Following times, it will:
Change the text of as many labels that are already added as possible to be that of as many of the values in results as possible
If there are any labels left that haven't been changed, remove those, as they are not necessary. Else, add as many new labels as needed.
This makes sense to me. If this algorithm is not what I should be doing, then stop reading now and post an answer with a better algorithm. However, if you agree, then tell me what I've done wrong with my code:
int i, r, l;
for (i=0, r = results.length(), l = calcResPanel.getComponentCount(); i < r; i++)
if (i < l)
((BHSelectableLabel)calcResPanel.getComponent(i)).setText(results.get(i));
else
calcResPanel.add(new BHSelectableLabel(results.get(i)));
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(i);
The problem with this code is that it inconsistently leaves excess labels in calcResPane. If you think this algorithm is good in concept, then please tell me what is wrong with my code that makes it leave excess labels?
Answer
Such a simple answer, too. I feel SO smart ^^;
int i, r, l;
for (i=0, r = results.length(), l = calcResPanel.getComponentCount(); i < r; i++)
if (i < l)
((BHSelectableLabel)calcResPanel.getComponent(i)).setText(results.get(i));
else
calcResPanel.add(new BHSelectableLabel(results.get(i)));
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(r);
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(i);
You can never do a remove like that because you skip every 2nd item. Lets say you have 5 items and you try to delete them all:
The first time through the loop i = 0, so you remove item 0 and you are left with 1, 2, 3, 4.
Next time throught the loop i = 1, so you remove item 2 and you are left with 1, 3, 4.
I hope you get the pattern.
The solution is to remove items from the end, one at a time.

Categories