// TestRadioButton.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class TestRadioButton extends JFrame implements ItemListener{//创建三个单选按钮private JRadioButton rb1 = new JRadioButton("居左对齐",false);private JRadioButton rb2 = new JRadioButton("居中对齐",false);private JRadioButton rb3 = new JRadioButton("居右对齐",false);//创建一个按钮组,用于实现单选按钮之间的互斥private ButtonGroup group = new ButtonGroup();private JTextField jtf = new JTextField("Hello");//构造方法public TestRadioButton(){setTitle("单选按钮");JPanel p1 = new JPanel();p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,10));//将三个单选按钮添加到面板p1上p1.add(rb1);p1.add(rb2);p1.add(rb3);//将三个单选按钮添加到按钮组group中,实现三个按钮之间的互斥group.add(rb1);group.add(rb2);group.add(rb3);//将面板p1和文本框jtf分别添加到内容窗格的相应区域getContentPane().add(p1,BorderLayout.CENTER);getContentPane().add(jtf,BorderLayout.NORTH);//为三个单选按钮注册ItemEvent事件的监听器rb1.addItemListener(this);rb2.addItemListener(this);rb3.addItemListener(this);}//事件处理方法,在产生ItemEvent事件是调用public void itemStateChanged(ItemEvent e){//判断事件源是否是单选按钮if(e.getSource() instanceof JRadioButton){//判断哪个单选按钮是否处于选中状态,如果选中则设置文本框的相应对齐方式if(rb1.isSelected())jtf.setHorizontalAlignment(JTextField.LEFT);if(rb2.isSelected())jtf.setHorizontalAlignment(JTextField.CENTER);if(rb3.isSelected())jtf.setHorizontalAlignment(JTextField.RIGHT);}}public static void main(String[] args){TestRadioButton frame = new TestRadioButton();frame.setSize(250,100);frame.setDefaultCloseOperation(3);frame.setVisible(true);}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。