Reputation: 950
I have a JComboBox
with only one value in the start and have one MouseListener connected to it. When I click on the JComboBox
I fill it with some new values. But the popupMenu are of the size of one element on the first click on the JComboBox
. The second time all values will appear as normal.
Any idea how I can make the comboBox update its popupMenu directly after I have updated its content?
Example program:
public class ComboBoxUpdate extends JFrame implements MouseListener {
private JComboBox<String> box;
public ComboBoxUpdate(){
// Init
JPanel panel = new JPanel();
box = new JComboBox<String>();
box.addItem("from start");
// Add listener
Component[] comps = box.getComponents();
for(int i = 0; i < comps.length; i++)
comps[i].addMouseListener(this);
panel.add(box);
this.add(panel);
this.pack();
this.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
if(box.getItemCount() == 1){
box.removeAllItems();
box.addItem("item 1");
box.addItem("item 2");
box.addItem("item 3");
}
}
public static void main(String[] args){
new ComboBoxUpdate();
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
Upvotes: 0
Views: 2108
Reputation: 807
I think it's the better solution:
public class ComboBoxUpdate extends JFrame implements PopupMenuListener {
private JComboBox box;
public ComboBoxUpdate() {
// Init
JPanel panel = new JPanel();
box = new JComboBox();
box.addItem("from start");
box.addPopupMenuListener(this);
panel.add(box);
this.add(panel);
this.pack();
this.setVisible(true);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if (box.getItemCount() == 1) {
box.removeAllItems();
box.addItem("item 1");
box.addItem("item 2");
box.addItem("item 3");
}
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
}
Upvotes: 1
Reputation: 109815
I have a JComboBox with only one value in the start and have one MouseListener connected to it. When I click on the JComboBox I fill it with some new values
Item
(s) to JComboBox
on runtime could be add/remove/modify into XxxComboBoxModel
only
use DefaultComboBoxModel in the case that you'll change all Items
use MutableComboBoxModel for add/remove/modify Item(s) on runtime
Upvotes: 1
Reputation: 3602
Try mousePressed()
or mouseReleased()
events instead of mouseClicked()
event. Also you have to repaint()
to make the changes visible.
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
if(box.getItemCount() == 1){
box.removeAllItems();
box.addItem("item 1");
box.addItem("item 2");
box.addItem("item 3");
repaint();
}
}
Upvotes: 0