combobox selection

Hi guys,

Iam new to Listeners under Swing.Is working on a task under swing & came across the following problem.

Have a comboBox(Say testCombo) filled with some string values.When the user selects one item from thge popup menu or when he presses "Enter" I want to do some action.

Tried adding both the ItemListener & ActionListener to it,but then,

the events are generated even while the user is moving through items in the displayed popup menu or when I add I add some items in the combobox.Thats not what I want..

I want to do some action only when the user selects an item from the comboxbox.(Iam coming from the MFC world.In MFC, could achieve it on a comboclose up event )

How can I achieve this under swing...

Thanks..
[788 byte] By [Kohinoor24] at [2007-11-20 8:42:06]
# 1 Re: combobox selection
hi
jcomboBox is easy to use .in this code sea it and line start with ***
-------------------
package sorting;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class MainWindow extends JFrame{
private JButton start;
public JTextField size;
private JPanel contentPane;
private JLabel L;
private ViewControl a;
private String s;
***private JComboBox cb;
***private String ArrayType[] = {"Inverse Sorted","Random Array","Sorted Array"};
private int[] d;
public MainWindow(){
super("Sorting");

JLabel ArrayLabel = new JLabel();
L = new JLabel();
size = new JTextField();
***cb = new JComboBox(ArrayType);
start = new JButton();
ButtonHandler myhandler = new ButtonHandler();
start.addActionListener(myhandler);
this.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
contentPane = (JPanel)this.getContentPane();
//
// ArrayLabel
//
ArrayLabel.setForeground(new Color(219, 213, 213));
ArrayLabel.setText("Array Size 1 : 350");
//
// L
//
L.setForeground(new Color(208, 205, 205));
L.setText("Array Type");
//
// Size
//
size.setText("100");

//
// Start
//
start.setText("Start Sort");

//
// contentPane
//
contentPane.setLayout(null);
contentPane.setBackground(new Color(55, 21, 159));
addComponent(contentPane, ArrayLabel, 103,143,106,20);
addComponent(contentPane, L, 97,35,106,23);
addComponent(contentPane, size, 220,141,100,22);
addComponent(contentPane, cb, 221,36,100,22);
addComponent(contentPane, start, 323,251,83,28);
//
// MainWin
//
this.setTitle("Sorting ");
this.setLocation(new Point(200, 200));
this.setSize(new Dimension(464, 350));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);


//
// TODO: Add any constructor code after initializeComponent call
//

this.setVisible(true);

}
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
{
c.setBounds(x,y,width,height);
container.add(c);
}

public String selectedItem(){
System.out.println((String)cb.getSelectedItem());
return (String) cb.getSelectedItem();
}
public int[] getArray(){
return d;
}
public class ButtonHandler implements ActionListener {
public void actionPerformed ( ActionEvent e ){
if( e.getSource() == start ){

s=size.getText().toString();
int num = Integer.parseInt(s);
int[] data = new int[num];
Random generator = new Random();
*** if( (cb.getSelectedItem() == "Random Array" )){

//generate the data randomly in the array.
for(int i=0 ; i<data.length ; i++ )
data[i] = 1 + generator.nextInt(20);
d = data;
for(int i=0 ; i<num ; i++)
System.out.print(data[i]);
*** }else if (cb.getSelectedItem() == "Sorted Array" ){
int j = 0;
for(int i=0;i<data.length;i++){
if(i%(data.length/15)==0)
j++;
data[i]=j;
}
d = data;
}
*** else{
int j = 0;
for(int i=0;i<data.length;i++){
if(i%(data.length/15)==0)
j++;
data[data.length-i-1]=j;
}
d = data;
}
a = new ViewControl(num, data);
a.pack();
a.setVisible(true);
}
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception ex)
{
System.out.println("Failed loading L&F: ");
System.out.println(ex);
}
new MainWindow();
}
}
----------------------------
and
bassem_hassen at 2007-11-10 2:15:19 >
# 2 Re: combobox selection
What's the difference between 'moving through items in the popup' and 'selecting an item'? Every time you move to a new item, you are selecting that item.

If you want to know which item was selected when the popup went away, you can add a PopupMenuListener and handle popupMenuWillBecomeInvisible(..) and popupMenuCanceled(..). If the user hits escape, or the focus is lost (i.e. the selection is cancelled), popupMenuCanceled will be called before the popupMenuWillBecomeInvisible.

The most exciting phrase to hear in science -the one that heralds new discoveries- is not "Eureka!" but "That's funny...".
I. Asimov
dlorde at 2007-11-10 2:16:20 >
# 3 Re: combobox selection
What I meant was,the listener should be called only when user clicks an item from the comboPopup menu or when he presses "Enter".

But the action listener is getting called even if I move through the items in the popup,which I dont want...Also when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item & calls the action Listener,Which also I dont want.
Kohinoor24 at 2007-11-10 2:17:21 >
# 4 Re: combobox selection
What I meant was,the listener should be called only when user clicks an item from the comboPopup menu or when he presses "Enter".In what way does handling popupMenuWillBecomeInvisible(..) and popupMenuCanceled(..) not satisfy that requirement?
Also when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item & calls the action Listener,Which also I dont want.If you want to override the key handling of the combo box, you can either give it a KeySelectionManager to handle selections, or for full control of key handling, override processKeyEvent(..). If you just want to stop it selecting items by key, return -1 from the KeySelectionManager.selectionForKey(..) method:combo.setKeySelectionManager(new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1; // no item to be selected
}
});Alternatively, you can override selectWithKeyChar(..) and return false.

It may help to understand that the intended mode of use of the JComboBox is to make a selection from a list on a form. When the form is submitted, all the controls are queried for their values and acted on. It isn't difficult to act on a combo selection immediately, but you have to specify exactly what you want to happen in response to which events. The way controls in MFC work isn't necessarily any guide to the way they work in Swing, and familiarity with MFC may actually make things more confusing...

We are what we repeatedly do. Excellence, then, is not an act, but a habit...
Aristotle
dlorde at 2007-11-10 2:18:18 >
# 5 Re: combobox selection
Dlorde,Thank u very much...

That will do..
Kohinoor24 at 2007-11-10 2:19:18 >