this is my first question, so help me please. I try to save the value of the method getStelectedRow in a type int variable(row) to next can use the method getValueAt(row,column). My problem is the value of my variable, it's -1, and this means the row is not selected, but I'm selecting a row.
The error is the next:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
If need more details just say me. Thanks.
EDIT:
My code is:
int row = jTablePersonal.getSelectedRow();
String query = "select * from table where id ='"+jTablePersonal.getValueAt(row,0)+"'";
The error point to the variable "row" when I call the method "getValueAt(row,0)"
Seems like a newbie problem. Given your explanation
"My problem is the value of my variable, it's -1, and this means the row is not selected, but I'm selecting a row."
You do not have this code inside a listener, you have like it your constructor or something. You want to have the code inside the listener. Something like
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row != -1) {
// do something
}
}
});
If you are using the Netbeans GUI Builder tool, you can
From the design view right click the button and go to Events -> Action -> actionPerformed
Go to you source view and you should see some auto-generated code like
jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
Write the code there.
You should also take some time to read How to write Event Listeners. GUI Programs are event driven, so you need to learn how to respond to these events by registering listeners
the problem is about getSelectedRow();
getSelectedRow is only work if table is current selected
my suggestion is , make temp variable to get last selectedrow to prevent error ,like
if(table.getSelectedRow()!=-1)
{
int lastselected=table.getSelectedRow();
}
Related
Example:
I made a table, and I want a search box for each column. I hid the column titles with this code:
table.setTableHeader(null);
And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.
I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.
Is there any way to do it? Or all the thing i tried useless and there is much easy way to do it? I hope explained it right.
Note :
I have found this code.I dont even know if it does what i need. I did try it but getting error.
/** Default sort behaviour, plus every third click removes the sort. */
private final class CustomSorter extends MouseAdapter {
#Override public void mouseClicked(MouseEvent aEvent) {
int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
//build a list of sort keys for this column, and pass it to the sorter
//you can build the list to fit your needs here
//for example, you can sort on multiple columns, not just one
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
//cycle through all orders; sort is removed every 3rd click
SortOrder order = SortOrder.values()[fCountClicks % 3];
sortKeys.add(new RowSorter.SortKey(columnIdx, order));
fSorter.setSortKeys(sortKeys);
++fCountClicks;
}
private int fCountClicks;
}
}
And did try this and getting same error.
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.getRowSorter().toggleSortOrder(1);
}
});
Error:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
This is the code: Code
This is the what program looks like : Picture
In the ActionListener of your JButton you can try sorting the column with code like:
table.getRowSorter().toggleSortOrder(columnIndex);
This should allow you to click the button to reverse the sort order each time it is clicked.
Edit:
As I said in my comment you need to learn how to solve a NullPointerException.
The stack trace when I run the code states:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frame1$2.actionPerformed(frame1.java:83)
Line 83 is:
table.getRowSorter().toggleSortOrder(0);
So you have two variables at that statement:
table
table.getRowSorter()
It is up to you to determine which variable is null
So you add debug code before that statement:
System.out.println( table );
System.out.println( table.getRowSorter() );
If you do you will see that table.getRowSorter() returns null.
So now you can ask a proper question like:
"Why does table.getRowSorter() return null?"
The answer is simple you didn't set the properties of the table to do sorting.
This is easily done by adding:
table.setModel(model);
table.setAutoCreateRowSorter(true); // added
In the future do some basic debugging BEFORE asking a question. You can't code if you don't know the basics of debugging code.
My original answered assumed you new how to sort columns in a table when using the table header and you just wanted to know how to use a separate button. That is why a "MRE" should be posted with EVERY question so we don't have to guess what your code is really doing.
I have a GWT DataGrid with a multi-selection model and check-boxes to show selection/select/deselect rows. That's all well and good.
But, I also want to have a second, independent selection model. If a user double-clicks on a row, I want to handle that event, and for the event handler to know which row was double-clicked. The double-clicking should not affect the check-box selection.
I tried this:
final SelectionModel<MyRecord> selectionModel = new MultiSelectionModel...
//Yes I need a MultiSelectionModel
dataGrid.addDomHandler(new DoubleClickHandler() {
public void onDoubleClick(DoubleClickEvent event) {
selectionModel.get??? //no suitable getter for double-clicked
}
}, DoubleClickEvent.getType());
But ran into a dead-end when I found now way to get the double-clicked row in the event handler. One way would be to register both a Multi- and Single- selection model, but doubt DataGrid will support that.
Neither can I work out how to get the clicked row from the DoubleClickEvent object.
I have implemented a button cell with a FieldUpdater. This works, but it's not ideal.
Any suggestions?
If I understand correctly you want to get the index of the row.
You could do it like this: (this way you'll get the "Real" index)
AbstractSelectionModel<T> selectionModel = (AbstractSelectionModel<T>)dataGrid.getSelectionModel();
ArrayList<Integer> intList = new ArrayList<Integer>();
List<Row> list = (List<Row>)_dataProvider.getList();
int i = 0;
for(Row row : list)
{
if( selectionModel.isSelected(row) )
intList.add(i);
i++;
}
UPDATE:
To get only the current row you could do that:
datagrid.getKeyboardSelectedRow()
I'm 3 years too late to the party, but I think the more correct solution would be:
dataGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<YOUR_MODEL_TYPE>() {
#Override
public void onCellPreview(final CellPreviewEvent<YOUR_MODEL_TYPE> event) {
if (BrowserEvents.DBLCLICK.equalsIgnoreCase(event.getNativeEvent().getType())) {
int row = event.getIndex();
doStuff(row); // do whatever you need the row index for
}
}
});
So I have this project,
the source code is here.
When you run the project and goto Processing, there is a jcombobox there that is suppose to have an addActionListener.
p_customer_list = new JComboBox<>(customers_name);
pp_customer_list.setPreferredSize(new Dimension(360, 35));
panel_processing_header.add(pp_customer_list);
//pp_customer_list.addActionListener(this);
pp_customer_list.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
JComboBox tmpBox = (JComboBox) e.getSource();
int selected = tmpBox.getSelectedIndex();
pp_refresh_data(selected);
}
});
This is what I have so far, its suppose to find the selected index when the value of the combobox changes and pass it to pp_refresh_data() but for some reason it does not run (I tried putting a JOptionPane to see when the code is executed, and its only executed once when the program runs.)
Hard to tell from just a partial code snippet, but do you have 2 combos, one named "p_customer_list" and another named "pp_customer_list"?
This could be your problem. You may be adding the listener to the wrong combo, or you may be adding the wrong combo to your panel, or maybe you don't need two, or maybe...
Again, it's hard to tell from just a snippet.
I need to remove all items from the combo box
int itemCount = combo.getItemCount();
for(int i = 0; i < itemCount; i++){
combo.removeItemAt(0);
}
This code will remove all items except the last one. It gives a NullPointerException.
How to fix that?
The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.
However, I sugeest you should better use the removeAllItems(); method:
combo.removeAllItems();
How about JComboBox.removeAllItems()?
You can use
this.combo.removeAllItems();
to remove all the items in JComboBox.
In second line:
combo.removeItemAt(0);
I think instead of 0 it should be i.
do it in reverse order as:
for(int i=combo.getItemCount()-1;i>=0;i--){
combo.removeItemAt(i);
}
But in my case combo.removeAllItems() works fine
use .removeAllItems() methods to remove all items from combo box.
The assumption that it is related to another thread is not always true. It can be the thread itself causing the issue.
This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.
For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.
The solution to this is to move the code from actionPerformed() to e.g. mouseClicked() or another event handler depending on what you want to do.
removeAllItems() it does remove all things but after the add data to the combo box it will not show there ,the nullPointException will shows
Use this to remove all the elements from the combo box :
DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();
Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
do_run ();
}
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
if (n> 0) {
String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
}
}
The default behaviour in a JTable seems to be that if I reach the last row of a column and hit return, I am taken to the first row of the next column. Is there a way to avoid this? Please suggest a way that I could stay at the last row of the same column. I also want to avoid a situation where I am taken to the next column and then detect that and go back to the previous one, because I have some listeners associated with it.
Any help is appreciated.
to change any of the navigational behaviour, replace the default navigational actions with your own. Best by wrapping the defaults: conditionally either do the default or your custom stuff. Something like
Object key = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.get(KeyStroke.getKeyStroke("ENTER"));
final Action action = table.getActionMap().get(key);
Action custom = new AbstractAction("wrap") {
#Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectionModel().getLeadSelectionIndex();
if (row == table.getRowCount() - 1) {
// do custom stuff
// return if default shouldn't happen or call default after
return;
}
action.actionPerformed(e);
}
};
table.getActionMap().put(key, custom);