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()) {
...
}
@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) {
...
}
应用以上的方法,我们也可以类似的实现对其他组件的监听及处理。