How to use the Java.Swing.JRadioButton radio button
This article mainly introduces how to use the Java.Swing.JRadioButton radio button, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
1. Overview
Official JavaDocsApi:javax.swing.JRadioButton
JRadioButton, radio button.
Common construction methods of JButton:
/ / No text, JRadioButton () / / text is not selected, JRadioButton (String text) / / text is not selected, and specify whether to select JRadioButton (String text, boolean selected)
Common methods of JRadioButton:
/ / set the text of the radio button, Font and font color void setText (String text) void setFont (Font font) void setForeground (Color fg) / * the following method defines whether the radio button is selected in the javax.swing.AbstractButton base class * / / sets whether the radio button is selected void setSelected (boolean b) / / determines whether the radio button is selected boolean isSelected () / sets whether the radio button is available void setEnabled (boolean enable) / / sets the radio button by default, Pictures void setIcon (Icon defaultIcon) void setPressedIcon (Icon pressedIcon) void setDisabledIcon (Icon disabledIcon) / / set the spacing between pictures and text void setIconTextGap (int iconTextGap) JRadioButton common listeners: / / add state change listeners void addChangeListener (ChangeListener l)
ButtonGroup (button group): when there are multiple radio buttons, only one radio button is allowed to be selected, so you need to group the same type of radio buttons as follows:
/ / create a button group ButtonGroup btnGroup = new ButtonGroup (); / / add a radio button to the button group btnGroup.add (radioBtn01); btnGroup.add (radioBtn02)
two。 Code example
Package com.xiets.swing;import javax.swing.*;import java.awt.*;public class Main {public static void main (String [] args) throws AWTException {JFrame jf = new JFrame ("Test window"); jf.setSize (200,200); jf.setLocationRelativeTo (null); jf.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE); JPanel panel = new JPanel (); / / create two radio buttons JRadioButton radioBtn01 = new JRadioButton ("male"); JRadioButton radioBtn02 = new JRadioButton ("female") / / create a button group and add two radio buttons to the group ButtonGroup btnGroup = new ButtonGroup (); btnGroup.add (radioBtn01); btnGroup.add (radioBtn02); / / set the first radio button to select radioBtn01.setSelected (true); panel.add (radioBtn01); panel.add (radioBtn02); jf.setContentPane (panel); jf.setVisible (true);}}
Thank you for reading this article carefully. I hope the article "how to use the Java.Swing.JRadioButton Radio Button" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!