JAVA之获取JavaSwing单选框JRadioButton选中的值(内容)
生活随笔
收集整理的這篇文章主要介紹了
JAVA之获取JavaSwing单选框JRadioButton选中的值(内容)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JAVA之獲取JavaSwing單選框JRadioButton選中的值(內容)
package word;import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;import javax.print.attribute.standard.Severity; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton;public class www extends JFrame{JButton btn;private static JPanel pane1 ;public www() {JFrame frame = new JFrame("單選框"); //頂層容器frame.setSize(200, 200); //窗口大小pane1 = new JPanel(); //中間容器//單選框JRadioButton c1 = new JRadioButton("草莓",true);//創建單選框,true為默認選中,不需要可去掉JRadioButton c2 = new JRadioButton("檸檬");//創建單選框JRadioButton c3 = new JRadioButton("香蕉");//創建單選框ButtonGroup group = new ButtonGroup(); //創建單選框按鈕組JLabel l1 = new JLabel("模式:");group.add(c1);//將單選框組件加入單選框按鈕組,否則兩個都可以選擇group.add(c2);group.add(c3);pane1.add(l1);pane1.add(c1);//將單選框組件加入面板pane1.add(c2);pane1.add(c3);//按鈕btn = new JButton("你選擇的是:");pane1.add(btn);//將按鈕加入面板frame.add(pane1);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);//顯示btn.addActionListener(new ActionListener() {//按鈕監聽@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString info ="";//通過面板屬性名獲取到該面板上的所有組件System.out.println(info);for(Component c:pane1.getComponents()){if(c instanceof JRadioButton){if(((JRadioButton) c).isSelected()){info += ((JRadioButton)c).getText();}}}System.out.println(info);//輸出選擇的單選框文本JOptionPane.showMessageDialog(null, "你選擇了"+info);}});}public static void main(String[] args) {// TODO Auto-generated method stubnew www();}}輸出為:
總結
以上是生活随笔為你收集整理的JAVA之获取JavaSwing单选框JRadioButton选中的值(内容)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA之获取JavaSwing复选框J
- 下一篇: C语言学习之编程实现:输入长方形的两个边