I need to refresh drop down list item just before doping down. I choose focusGained
event. But when I do deactivate/activate form I have two events fired in actionPerformed
that prints out :
***null
***aaa
I was not duing any dropdown selection why they are there?
Is focusGained
right place to refresh items in JComboBox
? What is better place of doing that?
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxDemo extends JPanel
implements ActionListener , FocusListener {
JLabel picture;
public ComboBoxDemo() {
super(new BorderLayout());
JComboBox petList = new JComboBox();
petList.addItem("1");
petList.addItem("2");
petList.addItem("3");
petList.addActionListener(this);
petList.addFocusListener(this);
add(petList, BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder(200,200,200,200));
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
System.out.println("***"+ petName);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ComboBoxDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void focusGained(FocusEvent fe) {
JComboBox cb = (JComboBox)fe.getSource();
cb.removeAllItems();
cb.addItem("aaa");
}
public void focusLost(FocusEvent fe) {
}
}