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 ();
}
}
Related
My task is to enable removing Jlist selected elements when alt is pressed and jlist is clicked. I did this by adding mouse listener to my jlist:
list.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
java.util.List selectedItems = list.getSelectedValuesList();
if (e.isAltDown()){
for (Object o : selectedItems){
cm.removeElement(o); //cm is my custom model
}
}
}
});
My issue is that when there are two elements selected and I click the list with alt pressed only nearest element gets selected and is removed then. I have no clue how to remove several elements with this input combination.
The problem is that the mouse click clears all the previous selections and then selects the row you just clicked on. So therefore only that row is deleted.
So instead you should be handling a "right mouse" click and then use the right mouse button only for the deletion of the item.
if (e.isAltDown() && SwingUtilities.isRightMouseButton(e)) {
Or if you really want to do this on a left mouse click then you would probably need to use a ListSelectionListener. Every time the selection changes you would need to use the getSelectedValuesList() method and save the List returned from the method. Then in the MouseListener you would access the saved List instead of getting the currently selected List of items.
I don't like this approach because the logic is now contained in two separate listeners. Although I guess you could create a class that implement both the selection listener and the mouse listener.
This is not a perfect answer. But it solves the issue.
I just tried to see how the selection event works. When he selection happens an Mouse pressed event is triggered and then the Selection happens. So the MouseListeners which are already added to the component are responsible to make the selection. Removing the MouseListeners which are already in place would prevent the selection happen using mouse. So i did this.
MouseListener[] adapters = list.getMouseListeners();
for (int i = 0; i < adapters.length; i++) {
list.removeMouseListener(adapters[i]);
}
Now user will not be able to do the selection using mouse but he will be make the selection using keyboard. So the below would work.
list.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
java.util.List selectedItems = list.getSelectedValuesList();
if (e.isAltDown()){
for (Object o : selectedItems){
model.removeElement(o); //cm is my custom model
}
}
}
});
I think the answer given by camickr, should be followed.
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();
}
I need to save the values in my jcombobox at the runtime. What I am trying to do is after clicking on a button, I am setting it to editable = true. Then type the value in the combobox, but it doesn't save.
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
cb_bkname.getText();
cb_bkname.addItem(evt);
}else{
cb_bkname.setEditable(false);
}
}
I have already added some elements in it on the designing level, but it's limited if some random value comes then its a problem.
Because it is possible to add / remove Item(s) to / from the DefaultComboBoxModel underlaying the JComboBox, the same action (by default) is possible from outside.
You have to use MutableComboBoxMode to add / remove Item(s) to / from JComboBox that fires event from itself (view_to_model).
There are excellent examples of MutableComboBoxModel by #Robin here and here.
For better help sooner post an SSCCE, for future readers, otherwise search for extends AbstractListModel implements MutableComboBoxModel.
it can't possibly work the way you're trying it.
the comboBox has to be editable before you click the button then you just need this line
cb_bkname.addItem(((JTextField)cb_bkname.getEditor().getEditorComponent()).getText());
Try this
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
String newItem=cb_bkname.getText();
cb_bkname.addItem(newItem);
}else{
cb_bkname.setEditable(false);
}
}
if(incasationBegin > 0)
{
int anwser = JOptionPane.showConfirmDialog(null, Config.QUESTION,"Confirm", JOptionPane.YES_NO_OPTION);
if(anwser == 1)
{
jList0.setSelectedIndex(incasationBegin);
return;
}
}
incasationBegin = jList0.getSelectedIndex();
How do I setSelectedIndex without calling jList0ListSelectionValueChanged action? Because when I click on option confirm popup and when I click NO, the new item is still selected. I have tried to add incasationBegin =0; before return, but then on first click confirm popup.
Let me see if i understood you correctly. You are adding a ListSelectionListener to the JList and want to prevent your call to setSelectedIndex from firing the valueChanged event, is that it?
You can try a lot of different approaches here:
Delay your call to jList0.addListSelectionListener(... in such way that no Listener exists when you call setSelectedIndex.
Have the listener valueChanged method check for some "enabled condition", for example read a boolean isEnabled. Set this condition to false before calling setSelectedIndex and to true after that.
Call jList0.removeListSelectionListener(.. before the call to setSelectedIndex. Add the listener to the list again after the call.
I have an ActionListener attached to a JComboBox(uneditable). Once an item from the JComboBox is selected, I have to make the next button in the frame visible.
The skeleton of the code looks like this:
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==jComboBox){
if(jComboBox.getSelectedIndex()==-1)
//Display an alert message
else{
nextButton.setVisible(true);
//Do other actions
}
}
}
It is found that actionPerformed is called only when the second, third, fourth (and so on) items are selected. But actionPerformed is not called when the first item is selected the very first time. But if the first item is selected after selecting other items actioPerformed gets called and the code works fine.
This error appears on some systems and doesn't on other systems. Any help in this regard would be appreciated.
Thanks in Advance!!
This is the normal behavour. The ActionEvent is not fired when you reselect the same item. If you want the event to be fired when you create the combo box then your code should be something like:
JComboBox comboBox = new JComboBox(...);
comboBox.setSelectedIndex(-1); // remove automatic selection of first item
comboBox.addActionListener(...);
comboBox.setSelectedIndex(0);
or
JComboBox comboBox = new JComboBox();
comboBox.addActionListener(...);
comboBox.addItem(...);
comboBox.addItem(...);
Seems like you first condition is a little wrong.
If you want to execute certain code if no item is in your JComboBox, you should check content size : jComboBox.getItemCount()==0 instead of jComboBox.getSelectedIndex()==-1, because selected index can depend upon various conditions, while getItemCount() is only 0 when, well, combo box is empty :-)