为了账号安全,请及时绑定邮箱和手机立即绑定

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

/ 猿问

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

慕姐829404 2019-02-12 14:10:32

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


查看完整描述

2 回答

?
慕容708150

单选按钮添加监听事件,当选中某个单击值时,你可以做一些你想做的事,下面是个简单的例子。有问题再追问吧,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();
}
}



查看完整回答
反对 回复 2019-03-18
?
慕斯卡3215842

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);
}

}



查看完整回答
反对 回复 2019-03-18
  • 2 回答
  • 0 关注
  • 157 浏览
我要回答

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信