I have a button click event on which i am getting a column value, if a Table row is selected. But if i don't select the row and click the button i get the error: java.lang.ArrayIndexOutOfBoundsException:-1 my question is how can i check to see if a row has been selected pseudocode: if(Row == selected) { execute }
java code i have:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
int row = Table.getSelectedRow();
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation hire
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Thank you for your help.
Stop and think logically about your problem before you're tempted to post. Take a break from coding if you need to -- once you take a break, the solution to the problem often presents itself in short order.
int row = Table.getSelectedRow();
if(row == -1)
{
// No row selected
// Show error message
}
else
{
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
// do whatever you need to do with the data from the row
}
When no row is selected, getSelectedRow() returns -1.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = Table.getSelectedRow();
if (row > -1) {
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation here
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
if row > -1 then you know a row has been selected.
see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()
Related
I have a jButton and when it is clicked currently I can select multiple rows and I am able to delete all of them. I am trying to make a message pop up if no row is selected to warn the user. I tried different things, but I couldn't manage it in the end unfortunately.
private void silButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int[] selectedItems = jTable2.getSelectedRows();
for (int i = 0; i < selectedItems.length; i++) {
String cell = (jTable2.getModel().getValueAt(selectedItems[i], 0)).toString();
System.out.println(cell);
String query="DELETE FROM Musteriler WHERE id="+cell+"";
PreparedStatement pst = connection.prepareStatement(query);
int rs = pst.executeUpdate();
}
loadTable();
cleanFields();
} catch (Exception e) {
System.out.println(e);
}
}
Simply just test that selectedItems length is zero or not:
if(selectedItems == null || selectedItems.length() < 1) {
showPopup();
}
API reference:
public int[] getSelectedColumns​()
Returns:
an array of integers containing the indices of all selected columns, or an empty array if no column is selected.
Basically you should check if the selectedItems is empty and show your modal dialog.
The porblem is that even I change cell value to the same exact value it counts as a change. So for example if I double click a cell and don't change its value my program proceeds to write it to the server.
How can I make that only cells that have their values changed, for instance (x -> y) write to server. (x -> x) do nothing.
Code below:
Misc_Table.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
Doo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
Object value = model.getValueAt(row, col);
int selected = (int) Functions_ComboBox.getSelectedIndex();
if(selected == 0){
String val = (String) value;
int int_Val = Integer.parseInt(val);
BackEnd.WriteMultiple_16Bit(unitID, row, int_Val , 1);
}
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(MISC,"Wrong number format.");
} catch (Exception e2) {
}
}
});
}
});
You can use the Table Cell Listener.
The TableCellListener replaces the TableModelListener and will only generate events when the data has actually changed, not when the editor is stopped. You just provide an Action to be invoked when the data changes.
a question about removing unused rows in jtable i am using DefualtTableModel my table already has some data & when i update it leave some columns empty to update theme later so they are null column.. i want to remove theme with a push button before saving data.. i actually tried this code:
private void btn_ClearActionPerformed(java.awt.event.ActionEvent evt) {
table.setAutoCreateRowSorter(true);
TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
sorter.setRowFilter(new RowFilterImpl());
}
i also tried this:
private void btn_ClearActionPerformed(java.awt.event.ActionEvent evt) {
table.setAutoCreateRowSorter(true);
TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
#Override
public boolean include(RowFilter.Entry<? extends TableModel, ? extends Integer> entry) {
boolean included = true;
Object cellValue = entry.getModel().getValueAt(entry.getIdentifier(), 0);
if (cellValue == null || cellValue.toString().trim().isEmpty()) {
included = false;
}
return included;
}
});
}
the code above is working but i don't like it becuase it resizes rows after filtering so i want to do something with model.remove(); using if conditions.. and i want to specify columns for example column 7 & 12 and want to remove only empty rows in specified columns..
ok i tried this code:
for (int i = model.getRowCount() - 1; i >= 0; i--)
{
Object col1 = model.getValueAt( i,model.getColumnCount() - 6);
Object col2 = model.getValueAt( i,model.getColumnCount() - 11);
if (col1 == null || col2 == null)
model.removeRow(i);
}
i faced same problem and i found this code below cuasing that problem so i removed it ... i also found that it counts how many time you selected or clicked on a row and then resizes it as many you clicked!
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
int lastRow = -1;
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
if (lastRow != -1) {
table.setRowHeight(lastRow, table.getRowHeight());
}
int row = table.getSelectedRow();
table.setRowHeight(row, 23);
lastRow = row;
}
}
});
any idea guys?
thanx in advance
Create a loop to remove the data from the model.
Maybe something like:
for (int i = model.getRowCount() - 1; i >= 0; i--)
{
if (column?? == null && column?? == null)
model.removeRow(i);
}
added the problem above in table.setRowHeight();
Well, that should have been part of the original question. How do we know you have custom logic doing something strange???
In the future post a proper SSCCE that demonstrates the problem so we don't have to guess what you are doing.
i get the same problem it resizes rows
Then remove the listener:
remove the listener
delete the rows
add the listener
I have a JTable which has 2 columns
column 0 username
column 1 password.
for the password column it will be encrypted to SHA256.
Basically what I want to achieve is it will update all the rows in my password column to SHA256 that I have edited after my button is pressed.
so..
I have a RowData class, this will store the text being edited and the position of the text
being edited(rows,columns).
public class RowData {
int rows = 0, columns = 0;
String text = " ";
public RowData(String text,int rows, int columns) {
setEditedRows(rows);
setEditedColumns(columns);
setEditedText(text);
}
public int getEditedRows() {
return rows;
}
public int getEditedColumns() {
return columns;
}
public String getEditedText() {
return text;
}
public void setEditedRows(int rows) {
this.rows = rows;
}
public void setEditedColumns(int columns) {
this.columns = columns;
}
public void setEditedText(String text) {
this.text = text;
}
}
I wrote a TableModelListener.. I have an List to store the text and the rows and columns
after the table has changed
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel) e.getSource();
//System.out.println(model.getValueAt(row, column));
if(column == 1) {
String data = (String) model.getValueAt(row, column);
System.out.println(data);
dataList.add(new RowData(data,row,column));
}
}
});
In my button I loop through the list and retrieve the rows, and columns and text
and set the password to SHA256 to the JTable.
updateBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (table.getCellEditor() != null) {
table.getCellEditor().stopCellEditing();
for(int i = 0; i < dataList.size(); i++) {
String text = dataList.get(i).getEditedText();
int rows = dataList.get(i).getEditedRows();
int columns = dataList.get(i).getEditedColumns();
//System.out.println(dataList.get(i).getEditedText() + " " + dataList.get(i).getEditedRows() + dataList.get(i).getEditedColumns());
table.setValueAt(convertPassword.convertToSHA256(text), rows ,columns);
}
}
}
});
The result I get is I will keep printing the password endlessly in my console.
So I think that my logic is wrong and needed to be corrected.
table.setValueAt(convertPassword.convertToSHA256(text), rows ,columns);
When you change the TableModel the TableModelListener will be invoked again. The TableModelListener is invoked whether you change the data by using the JTable or by updating the TableModel directly.
The solution would be to remove the TableModelListener when you click on your button, at the start of your ActionListener. You would then need to add the TableModelListener back to the TableModel at the end of the code in case the user make further changes.
Another solution is to have 3 columns in the TableModel, username, password and sha256Password. Then you can use the JTable to display only the first two columns. See the removeColumn() method of JTable. Then your conversion code would update the TableModel using:
table.getModel().setValueAt(value, row, 2);
Now the code in your TableModel will be invoked, but because you check for updates to column 1, nothing will happen when you update column 2.
Then when you save the data you save the data from the TableModel.
Edit:
I must click into another cell before I can press my button to edit.
You need to stop the cell editing. See Table Stop Editing for a couple of solutions.
I using detaful table model
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
and I row count
int Row = model.getRowCount();
Here is which I add row and wish to diplay error when adding same items.
if (Row > 0) {
for(i=0;i<Row; i++){
if(jTable1.getValueAt(i,0).equals(name.getText())){
JOptionPane.showMessageDialog(null, "Can't add same item");
}
}
}else if (Row <99) {
model.addRow(new Object[] {name.getText(),address.getText(),Integer.parseInt(age.getText())});
}
I guess wrong at if else statement?
Because I can add the 1st row and I can't add for 2nd row.
Thanks for help
Not sure what you have in your other variables, but I guess you have a discrepancy between product_id and name, perhaps?
Wouldn't it be more like
if(jTable1.getValueAt(i,0).equals(name.getText())){
UPDATE:
Try rewriting it like this:
int Row = model.getRowCount();
int boolean exists = false;
for(i=0;i<Row; i++){
if(jTable1.getValueAt(i,0).equals(name.getText())){
JOptionPane.showMessageDialog(null, "Can't add same item");
exists = true;
break;
}
}
if (!exists && Row < 99) {
model.addRow(new Object[] {name.getText(),address.getText(),Integer.parseInt(age.getText())});
}