Java Swing How to - Fill JComboBox with ItemListener and JRadioButton








Question

We would like to know how to fill JComboBox with ItemListener and JRadioButton.

Answer

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from  w  ww.j a  v a2 s .c o  m
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class Main extends JFrame {
  JRadioButton rOne = new JRadioButton("One"),  rTwo = new JRadioButton("Two");
  ButtonGroup group;
  JComboBox combo;
  JLabel label;

  public Main() {
    rOne.addActionListener(new ROneAction());
    rTwo.addActionListener(new RTwoAction());
    group = new ButtonGroup();
    group.add(rOne);
    group.add(rTwo);

    combo = new JComboBox();
    combo.addItem("No Values");
    combo.addPopupMenuListener(new PopupMenuListener() {
      public void popupMenuCanceled(PopupMenuEvent evt) {
      }
      public void popupMenuWillBecomeInvisible(
          PopupMenuEvent evt) {
        jComboBox1PopupMenuWillBecomeInvisible(evt);
      }

      public void popupMenuWillBecomeVisible(
          PopupMenuEvent evt) {
      }
    });

    label = new JLabel("labelLabel");

    this.setLayout(new FlowLayout());
    this.add(rOne);
    this.add(rTwo);
    this.add(combo);
    this.add(label);
    this.pack();
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  private class ROneAction implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
      combo.removeAllItems();
      combo.addItem("One");
    }
  }
  private class RTwoAction implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
      combo.removeAllItems();
      combo.addItem("Two");
    }
  }
  private void jComboBox1PopupMenuWillBecomeInvisible(
      javax.swing.event.PopupMenuEvent evt) {
    label.setText("selected");
  }
  public static void main(String[] args) {
    new Main();
  }
}