package com.company; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class Main extends JFrame{ public Main(){ setBounds(100,100,180,110); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c=getContentPane(); c.setLayout(new FlowLayout()); JRadioButton left=new JRadioButton("向右走"); JRadioButton right=new JRadioButton("向左走"); c.add(left); c.add(right); ButtonGroup group=new ButtonGroup();//按钮组 group.add(left);//把按钮放在按钮组中 group.add(right); left.setSelected(true); JButton bun=new JButton("打印"); bun.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println(left.getText()+"按钮选中状态:"+left.isSelected()); System.out.println(right.getText()+"按钮选中状态:"+right.isSelected()); group.clearSelection();//按钮组选项清空 } }); c.add(bun); setVisible(true); } public static void main(String[] args) { new Main(); // write your code here } }
package com.company; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class Main extends JFrame{ public Main(){ setBounds(100,100,180,110); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c=getContentPane(); c.setLayout(new FlowLayout()); JRadioButton left=new JRadioButton("向右走"); JRadioButton right=new JRadioButton("向左走"); c.add(left); c.add(right); ButtonGroup group=new ButtonGroup();//按钮组 group.add(left);//把按钮放在按钮组中 group.add(right); left.setSelected(true); JButton bun=new JButton("打印"); bun.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println(left.getText()+"按钮选中状态:"+left.isSelected()); System.out.println(right.getText()+"按钮选中状态:"+right.isSelected()); group.clearSelection();//按钮组选项清空 } }); c.add(bun); setVisible(true); } public static void main(String[] args) { new Main(); // write your code here } }
package com.company; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class Main extends JFrame{ public Main(){ setBounds(100,100,180,110); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c=getContentPane(); c.setLayout(new FlowLayout()); JRadioButton left=new JRadioButton("向右走"); JRadioButton right=new JRadioButton("向左走"); c.add(left); c.add(right); ButtonGroup group=new ButtonGroup();//按钮组 group.add(left);//把按钮放在按钮组中 group.add(right); left.setSelected(true); JButton bun=new JButton("打印"); bun.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println(left.getText()+"按钮选中状态:"+left.isSelected()); System.out.println(right.getText()+"按钮选中状态:"+right.isSelected()); group.clearSelection();//按钮组选项清空 } }); c.add(bun); setVisible(true); } public static void main(String[] args) { new Main(); // write your code here } }