java中swing怎么将单选按钮的值返回给调用它的函数?

 我来答
zhaotao_king
推荐于2016-01-19 · TA获得超过2455个赞
知道大有可为答主
回答量:863
采纳率:0%
帮助的人:1126万
展开全部
为单选按钮添加监听事件,当选中某个单击值时,你可以做一些你想做的事,下面是个简单的例子。有问题再追问吧,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();
}
}
yinyue_yymusic
2012-05-08 · TA获得超过156个赞
知道答主
回答量:178
采纳率:0%
帮助的人:73.6万
展开全部
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);
}

}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式