为单选按钮添加监听事件,当选中某个单击值时,你可以做一些你想做的事,下面是个简单的例子。有问题再追问吧,good lucky、!~
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class MyRadioButton extends JFrame implements ActionListener {
private JLabel lj = new JLabel("默认");
public MyRadioButton() {
// TODO Auto-generated constructor stub
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
JRadioButton j1 = new JRadioButton("男");
JRadioButton j2 = new JRadioButton("女");
j1.addActionListener(this);
j2.addActionListener(this);
c.add(j1);
c.add(j2);
c.add(lj);
this.setSize(200, 200);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String eSource = e.getActionCommand();
//在这里调用方法,进行赋值/传值
if("男".equals(eSource)) {
lj.setText("男");
}
if("女".equals(eSource)) {
lj.setText("女");
}
}
public static void main(String[] args) {
new MyRadioButton();
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class JRadioButtonJFrame extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
public JTextArea textArea;
/**
*
*
*/
public JRadioButtonJFrame() {
initUI();
}
/**
*
*
*/
private void initUI() {
this.setLayout(new BorderLayout());
JRadioButton button1 = new JRadioButton("man");
JRadioButton button2 = new JRadioButton("women");
button1.addActionListener(this);
button2.addActionListener(this);
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.SOUTH);
textArea = new JTextArea();
add(textArea, BorderLayout.CENTER);
}
/**
*
*/
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("man")) {
textArea.setText("man");
} else if (command.equals("women")) {
textArea.setText("women");
}
}
/**
* @param args
*/
public static void main(String[] args) {
JRadioButtonJFrame frame = new JRadioButtonJFrame();
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}