发布网友 发布时间:2024-10-24 16:30
共2个回答
热心网友 时间:2024-11-09 21:57
package test;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class MyUI extends JFrame implements ItemListener {
private static final long serialVersionUID = 1L;
private JLabel info;
private JCheckBox cb1, cb2, cb3;
private JRadioButton male, famale;
private ButtonGroup sexGroup;
private JButton ok;
public MyUI(){
this.setTitle("Test Java UI");
this.setSize(500, 300);
this.setLayout(new GridLayout(4, 1));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
JPanel temp = new JPanel();
// 你的选择
info = new JLabel();
temp.add(info);
this.add(temp);
// 单选
male = new JRadioButton("男");
famale = new JRadioButton("女");
male.addItemListener(this);
famale.addItemListener(this);
sexGroup = new ButtonGroup();
sexGroup.add(male);
sexGroup.add(famale);
temp = new JPanel();
temp.add(new JLabel("性 别:", Label.RIGHT));
temp.add(male);
temp.add(famale);
this.add(temp);
// 复选框
temp = new JPanel();
cb1 = new JCheckBox("足球");
cb2 = new JCheckBox("篮球");
cb3 = new JCheckBox("游戏");
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
temp.add(new JLabel("兴 趣:", JLabel.RIGHT));
temp.add(cb1);
temp.add(cb2);
temp.add(cb3);
this.add(temp);
// 确定按钮
temp = new JPanel();
ok = new JButton("确 定");
temp.add(ok);
this.add(temp);
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
StringBuilder buffer = new StringBuilder();
buffer.append("性别:");
if (male.isSelected()){
buffer.append("男");
} else if (famale.isSelected()) {
buffer.append("女");
}
boolean flag = false;
buffer.append(" 兴趣:");
if (cb1.isSelected()) {
buffer.append("足球、");
flag = true;
}
if (cb2.isSelected()) {
buffer.append("篮球、");
flag = true;
}
if (cb3.isSelected()) {
buffer.append("游戏、");
flag = true;
}
String tempStr = "";
if (flag) {
tempStr = buffer.toString();
}
info.setText(tempStr.substring(0, tempStr.length()-1));
}
});
}
public static void main(String[] args) {
new MyUI();
}
@Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
}
}
热心网友 时间:2024-11-09 21:59
CheckBox Radio CheckBox