Java图形界面中单选按钮JRadioButton和按钮Button事件处理

Java图形界面设计完成后,就可以进行事件监听处理啦,在这里简单的实现单选按钮以及按钮的响应事件。

(1)单选按钮的监听,方法一,自定义内部类

//声明

JRadioButton r1;

//实例化内部类对象

private RadioButtonListener radioButtonListener = new RadioButtonListener();

//初始化

r1 = new JRadioButton("0.没有");

//添加到面板

add(r1);

//添加监听器

r1.addActionListener(radioButtonListener);

//自定义内部类重写ActionListener接口中的actionPerformed方法实现自己要处理的业务

private class RadioButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent arg0) {
     JRadioButton temp = (JRadioButton) arg0.getSource();
     if (temp.isSelected()) {
      ...
     }
   }
 }


(2)按钮的监听,方法二,直接继承ActionListener接口

JButton button;

button = new JButton("确定");

add(button);

//添加监听器

button.addActionListener(this);

//重写方法处理业务

@Override
 public void actionPerformed(ActionEvent e) {

  ...

}


应用以上的方法,我们也可以类似的实现对其他组件的监听及处理。

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问!下面是一个简单的Java程序,实现了一个“教师信息维护的图形用户界面”。 ```java import javax.swing.*; import java.awt.*; public class TeacherInfoUI extends JFrame { private JRadioButton maleButton; private JRadioButton femaleButton; private JButton addButton; private JButton deleteButton; public TeacherInfoUI() { // 设置窗体位置和大小 setBounds(300, 50, 380, 220); // 设置布局方式 setLayout(new FlowLayout()); // 创建性别面板 JPanel genderPanel = createGenderPanel(); add(genderPanel); // 创建操作面板 JPanel operationPanel = createOperationPanel(); add(operationPanel); // 设置窗体可见 setVisible(true); } private JPanel createGenderPanel() { JPanel genderPanel = new JPanel(); // 创建性别单选按钮和标签 maleButton = new JRadioButton("男", true); femaleButton = new JRadioButton("女", false); JLabel genderLabel = new JLabel("性别:"); // 将单选按钮和标签添加到面板 genderPanel.add(genderLabel); genderPanel.add(maleButton); genderPanel.add(femaleButton); // 设置单选按钮为一组,实现互斥效果 ButtonGroup genderGroup = new ButtonGroup(); genderGroup.add(maleButton); genderGroup.add(femaleButton); return genderPanel; } private JPanel createOperationPanel() { JPanel operationPanel = new JPanel(); // 创建添加和删除按钮 addButton = new JButton("添加"); deleteButton = new JButton("删除"); // 将按钮添加到面板 operationPanel.add(addButton); operationPanel.add(deleteButton); return operationPanel; } public static void main(String[] args) { TeacherInfoUI teacherInfoUI = new TeacherInfoUI(); } } ``` 在程序,我们创建了一个TeacherInfoUI类,继承自JFrame。在构造函数,我们设置了窗体的位置和大小,并调用了两个私有方法来创建性别面板和操作面板。在main方法,我们创建了一个TeacherInfoUI对象,从而启动了程序。 运行程序后,您可以看到一个包含性别单选按钮和添加、删除按钮的GUI界面。您可以根据自己的需求来进一步完善程序。希望这个程序对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值