Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to reset or clear JComboBox ?

5,170 views
Skip to first unread message

Bernard

unread,
Sep 17, 2001, 10:19:30 AM9/17/01
to
/*
Hi all,
I am trying to get a JComboBox to reset / clear itself to the
null entry (or the -1 selectedIndex) without any luck.

The purpose is to let the user reset the null entry initial
condition AFTER an entry was made.

My idea was to add an additional empty entry with a 0 length
display-string, that, when selected by the user, resets the JComboBox
in the same way as the button.

The best thing would be if the user could reset the box by
pressing the Delete key.

I could not get this to work so I tried to insert a special blank
entry that if selected, would trigger the reset in the same way as the
Reset button.

The example below shows the dilemma. Instead of jumping to
selectedIndex -1,
it jumps to 0.

How can I get the JComboBox to reset itself?

Many thanks,
Bernard

P.S.
I used the setEditable(true) option which I don't like it because I
thing it creates confusion by letting users type in values which is
not permitted in my case.


*/

import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;

class ComboBoxDemo extends JFrame {


JComboBox cBox;


public ComboBoxDemo () {

cBox = new JComboBox ();

getContentPane().add (cBox, BorderLayout.NORTH);


String[] items = {"0","1","2 (reset to -1)"};
for(int i = 0; i < items.length; i++){
cBox.addItem(items[i]);
}// for

// De-select
reset();


cBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cBoxActionPerformed(evt);
}
});


JButton jButtonReset = new JButton("Reset");

jButtonReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButtonResetActionPerformed(evt);
}
});


getContentPane().add (jButtonReset, BorderLayout.SOUTH);

addWindowListener (new MyWAdapter ());

}// constructor


public static void main (String [] args) {
Frame f = new ComboBoxDemo ();
f.pack();
f.show();
}// method


private void reset(){
cBox.setSelectedIndex(-1);
}// method


private void jButtonResetActionPerformed(ActionEvent evt) {
reset();
}// method

private void cBoxActionPerformed(ActionEvent evt) {
if(cBox.getSelectedIndex() == 2){
reset();
}// if
}// method


class MyWAdapter extends WindowAdapter {

public void windowClosing(WindowEvent event) {
System.exit (0);
}// method
}// inner class

}// class

Thomas Papendieck

unread,
Sep 18, 2001, 9:28:53 AM9/18/01
to
You could add an ActionListener to
<cBox.getEditor().getEditorComponent()>
and assign te statement
<cBox.removeAll()>
to the "VK_DELETE" in <keyPressed()> method.
0 new messages