⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 radiobuttonframe.java

📁 Eclipse程序设计经典教程+源代码 学习java的朋友可以看看
💻 JAVA
字号:
package component;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioButtonFrame extends JFrame implements ItemListener {
  JPanel contentPane;
  JRadioButton jRadioButton1 = new JRadioButton();
  JRadioButton jRadioButton2 = new JRadioButton();
  JRadioButton jRadioButton3 = new JRadioButton();
  ButtonGroup buttonGroup1 = new ButtonGroup();

  public RadioButtonFrame() {
    try {
      //窗口关闭时清空内存
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  
  public static void main(String[] args) {
    RadioButtonFrame frame = new RadioButtonFrame();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    //居中对齐
    frame.setLocation((screenSize.width - frameSize.width) / 2,
        (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
  }

  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(null);
    this.setSize(new Dimension(400, 300));
    this.setTitle("单选框示例");
    jRadioButton1.setText("单选框1");
    jRadioButton1.setBounds(new Rectangle(142, 61, 91, 25));
    jRadioButton1.addItemListener(this);
    jRadioButton2.setText("单选框2");
    jRadioButton2.setBounds(new Rectangle(142, 122, 91, 25));
    jRadioButton2.addItemListener(this);
    jRadioButton3.setText("单选框3");
    jRadioButton3.setBounds(new Rectangle(142, 182, 91, 25));
    jRadioButton3.addItemListener(this);
    buttonGroup1.add(jRadioButton1);
    buttonGroup1.add(jRadioButton2);
    buttonGroup1.add(jRadioButton3);
    contentPane.add(jRadioButton2, null);
    contentPane.add(jRadioButton3, null);
    contentPane.add(jRadioButton1, null);
  }
  public void itemStateChanged(ItemEvent e) {
    //取得单选框
    JRadioButton tempRadioButton = (JRadioButton)e.getSource();
    if(tempRadioButton.isSelected()){
      JOptionPane.showMessageDialog(null, tempRadioButton.getText() + "被选择.");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -