Java Tutorial/Swing/JRadioButton

Материал из Java эксперт
Перейти к: навигация, поиск

Creating JRadioButton Components

  1. A JRadioButton represents a radio button.
  2. You can use multiple JRadioButtons to represents a selection from which only one item can be selected.
  3. To indicate a logical grouping of radio buttons, you use a javax.swing.ButtonGroup object.
  4. To programmatically select a JRadioButton, you pass true to its setSelected method.



public JRadioButton()
JRadioButton aRadioButton = new JRadioButton();
public JRadioButton(Icon icon)
JRadioButton aRadioButton = new JRadioButton(new DiamondIcon(Color.CYAN, false));
aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));
public JRadioButton(Icon icon, boolean selected)
JRadioButton aRadioButton = new JRadioButton(new DiamondIcon(Color.CYAN, false),  true);
aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));
public JRadioButton(String text)
JRadioButton aRadioButton = new JRadioButton("4 slices");
public JRadioButton(String text, boolean selected)
JRadioButton aRadioButton = new JRadioButton("8 slices", true);
public JRadioButton(String text, Icon icon)
JRadioButton aRadioButton = new JRadioButton("12 slices",  new DiamondIcon(Color.CYAN, false));
aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));
public JRadioButton(String text, Icon icon, boolean selected)
JRadioButton aRadioButton = new JRadioButton("16 slices",  new DiamondIcon(Color.CYAN, false), true);
aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));
public JRadioButton(Action action)
Action action = ...;
JRadioButton aRadioButton = new JRadioButton(action);





Customizing JRadioButton Look and Feel

Property StringObject TypeRadioButton.backgroundColorRadioButton.borderBorderRadioButton.darkShadowColorRadioButton.disabledTextColorRadioButton.focusColorRadioButton.focusInputMapObject[ ]RadioButton.fontFontRadioButton.foregroundColorRadioButton.gradientListRadioButton.highlightColorRadioButton.iconIconRadioButton.interiorBackgroundColorRadioButton.lightColorRadioButton.marginInsetsRadioButton.rolloverBooleanRadioButton.selectColorRadioButton.shadowColorRadioButton.textIconGapIntegerRadioButton.textShiftOffsetIntegerRadioButtonUIString


Determining the Selected JRadioButton in a Button Group

import java.util.Enumeration;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  public static JRadioButton getSelection(ButtonGroup group) {
    for (Enumeration e = group.getElements(); e.hasMoreElements();) {
      JRadioButton b = (JRadioButton) e.nextElement();
      if (b.getModel() == group.getSelection()) {
        return b;
      }
    }
    return null;
  }
}





Event sequence: Action Event, Item Event and Change Event

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JRadioButtonEventSequence {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ActionListener actionListener = new ActionListener() {
      String lastSelected;
      public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton aButton = (AbstractButton)actionEvent.getSource();
        String label = aButton.getText();
        String msgStart;
        if (label.equals(lastSelected)) {
          msgStart = "Reselected: ";
        } else {
          msgStart = "Selected: ";
        }
        lastSelected = label;
        System.out.println(msgStart + label);
      }
    };
    ItemListener itemListener = new ItemListener() {
      String lastSelected;
      public void itemStateChanged(ItemEvent itemEvent) {
        AbstractButton aButton = (AbstractButton)itemEvent.getSource();
        int state = itemEvent.getStateChange();
        String label = aButton.getText();
        String msgStart;
        if (state == ItemEvent.SELECTED) {
          if (label.equals(lastSelected)) {
            msgStart = "Reselected -> ";
          } else {
            msgStart = "Selected -> ";
          }
          lastSelected = label;
        } else {
          msgStart = "Deselected -> ";
        }
        System.out.println(msgStart + label);
      }
    };
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changEvent) {
        AbstractButton aButton = (AbstractButton)changEvent.getSource();
        ButtonModel aModel = aButton.getModel();
        boolean armed = aModel.isArmed();
        boolean pressed = aModel.isPressed();
        boolean selected = aModel.isSelected();
        System.out.println("Changed: " + armed + "/" + pressed + "/" +
          selected);
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addChangeListener(changeListener);
    bRadioButton.addChangeListener(changeListener);
    aRadioButton.addActionListener(actionListener);
    bRadioButton.addActionListener(actionListener);
    aRadioButton.addItemListener(itemListener);
    bRadioButton.addItemListener(itemListener);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
  
}





Getting selected JRadioButton in a container

import java.awt.ruponent;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButtonSelectedElements {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ActionListener crustActionListener = new ActionListener() {
      String lastSelected;
      public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton aButton = (AbstractButton) actionEvent.getSource();
        String label = aButton.getText();
        String msgStart;
        if (label.equals(lastSelected)) {
          msgStart = "Reselected: ";
        } else {
          msgStart = "Selected: ";
        }
        lastSelected = label;
        System.out.println(msgStart + label);
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addActionListener(crustActionListener);
    bRadioButton.addActionListener(crustActionListener);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
    
    System.out.println(getSelectedElements(panel).hasMoreElements());
  }
  public static Enumeration<String> getSelectedElements(Container container) {
    Vector<String> selections = new Vector<String>();
    Component components[] = container.getComponents();
    for (int i=0, n=components.length; i<n; i++) {
      if (components[i] instanceof AbstractButton) {
        AbstractButton button = (AbstractButton)components[i];
        if (button.isSelected()) {
          selections.addElement(button.getText());
        }
      }
    }
    return selections.elements();
  }
}





Grouping JRadioButton Components in a ButtonGroup

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
class RadioButtonUtils {
  public static Container createRadioButtonGrouping(String elements[], String title) {
    JPanel panel = new JPanel(new GridLayout(0, 1));
    if (title != null) {
      Border border = BorderFactory.createTitledBorder(title);
      panel.setBorder(border);
    }
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton;
    for (int i = 0, n = elements.length; i < n; i++) {
      aRadioButton = new JRadioButton(elements[i]);
      panel.add(aRadioButton);
      group.add(aRadioButton);
    }
    return panel;
  }
}
public class GroupJRadioButton {
  private static final String sliceOptions[] = { "4", "8", "12", "16" };
  private static final String crustOptions[] = { "A", "B", "C", "D" };
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container sliceContainer = RadioButtonUtils.createRadioButtonGrouping(sliceOptions,
        "Slice Count");
    Container crustContainer = RadioButtonUtils.createRadioButtonGrouping(crustOptions,
        "Crust Type");
    frame.add(sliceContainer, BorderLayout.WEST);
    frame.add(crustContainer, BorderLayout.EAST);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Listening to JRadioButton Events with a ChangeListener

when the selected radio button is armed, pressed, selected, or released



import java.awt.GridLayout;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JRadioButtonChangeListener {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changEvent) {
        AbstractButton aButton = (AbstractButton)changEvent.getSource();
        ButtonModel aModel = aButton.getModel();
        boolean armed = aModel.isArmed();
        boolean pressed = aModel.isPressed();
        boolean selected = aModel.isSelected();
        System.out.println("Changed: " + armed + "/" + pressed + "/" +
          selected);
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addChangeListener(changeListener);
    bRadioButton.addChangeListener(changeListener);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
  
}





Listening to JRadioButton Events with an ActionListener

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButtonActionListener {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ActionListener sliceActionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton aButton = (AbstractButton) actionEvent.getSource();
        System.out.println("Selected: " + aButton.getText());
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addActionListener(sliceActionListener);
    bRadioButton.addActionListener(sliceActionListener);

    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Listening to JRadioButton Events with an ItemListener

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButtonItemListener {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ItemListener itemListener = new ItemListener() {
      String lastSelected;
      public void itemStateChanged(ItemEvent itemEvent) {
        AbstractButton aButton = (AbstractButton)itemEvent.getSource();
        int state = itemEvent.getStateChange();
        String label = aButton.getText();
        String msgStart;
        if (state == ItemEvent.SELECTED) {
          if (label.equals(lastSelected)) {
            msgStart = "Reselected -> ";
          }  else {
           msgStart = "Selected -> ";
          }
          lastSelected = label;
        }  else {
          msgStart = "Deselected -> ";
        }
        System.out.println(msgStart + label);
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addItemListener(itemListener);
    bRadioButton.addItemListener(itemListener);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
  
}





Reference to the last selected item and check for reselection

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButtonActionListenerSelectedItem {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Grouping Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(0, 1));
    ButtonGroup group = new ButtonGroup();
    JRadioButton aRadioButton = new JRadioButton("A");
    JRadioButton bRadioButton = new JRadioButton("B");
    ActionListener crustActionListener = new ActionListener() {
      String lastSelected;
      public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton aButton = (AbstractButton) actionEvent.getSource();
        String label = aButton.getText();
        String msgStart;
        if (label.equals(lastSelected)) {
          msgStart = "Reselected: ";
        } else {
          msgStart = "Selected: ";
        }
        lastSelected = label;
        System.out.println(msgStart + label);
      }
    };
    panel.add(aRadioButton);
    group.add(aRadioButton);
    panel.add(bRadioButton);
    group.add(bRadioButton);
    aRadioButton.addActionListener(crustActionListener);
    bRadioButton.addActionListener(crustActionListener);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Using JRadioButton

import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class JRadioButtonTest {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JRadioButton Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JRadioButton button1 = new JRadioButton("Red");
    JRadioButton button2 = new JRadioButton("Green");
    JRadioButton button3 = new JRadioButton("Blue");
    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);
    button1.setSelected(true);
    frame.add(new JLabel("Color:"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);
  }
}