这个Java代码使用的是Swing。我正在尝试生成一个表单,以便在其中涵盖Swing basic。它有标签,按钮,文本字段但单选按钮不起作用。请告诉我里面的错误。是因为我没有在面板中添加单选按钮吗?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Swingtrial extends JFrame {
final String[] sList
= {
"JANUARY",
"FEBRUARY",
"MARCH",
"APRIL",
"MAY",
"JUNE",
"JULY",
"AUGUST",
"SEPTEMBER",
"OCTOBER",
"NOVEMBER",
"DECEMBER",};
public Swingtrial() {
callGUI();
}
public void callGUI() {
int s[];
JPanel panel = new JPanel();
getContentPane().add(panel);
setTitle("TRIAL FORM");
panel.setLayout(null);
panel.setSize(200, 200);
JLabel lab = new JLabel("Name");
lab.setBounds(200, 60, 100, 25);
panel.add(lab);
JTextField name = new JTextField("first name");
name.setBounds(275, 60, 100, 25);
panel.add(name);
JTextField name1 = new JTextField("middle name");
name1.setBounds(380, 60, 100, 25);
panel.add(name1);
JTextField name2 = new JTextField("last name");
name2.setBounds(500, 60, 150, 25);
panel.add(name2);
JLabel age = new JLabel("Date of Birth");
age.setBounds(200, 100, 150, 25);
panel.add(age);
JComboBox date = new JComboBox();
date.setBounds(275, 100, 50, 25);
date.setBackground(Color.LIGHT_GRAY);
panel.add(date);
for (int i = 1; i <= 31; i++) {
extracted(date, i);
}
JComboBox drop = new JComboBox();
drop.setBounds(350, 100, 85, 25);
drop.setBackground(Color.LIGHT_GRAY);
panel.add(drop);
for (int iCtr = 0; iCtr < sList.length; iCtr++) {
drop.addItem(sList[iCtr]);
}
JComboBox yr = new JComboBox();
yr.setBounds(455, 100, 80, 25);
yr.setBackground(Color.LIGHT_GRAY);
panel.add(yr);
for (int i = 1900; i <= 2014; i++) {
extracted(yr, i); // not understood?????? :(
}
JLabel add = new JLabel("address");
add.setBounds(200, 150, 100, 25);
panel.add(add);
JTextField address = new JTextField("Adress");
address.setBounds(280, 150, 200, 40);
panel.add(address);
JRadioButton male = new JRadioButton("male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup bG = new ButtonGroup();
add(male);
bG.add(female);
this.setSize(100, 200);
this.setLayout(new FlowLayout());
this.add(male);
this.add(female);
male.setSelected(true);
this.setVisible(true);
JButton but = new JButton("ommm");
but.setBounds(50, 60, 80, 30);
panel.add(but);
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
private void extracted(JComboBox month, int i) {
month.addItem(i);
}
public static void main(String args[]) {
Swingtrial mainFrame = new Swingtrial();
mainFrame.setVisible(true);
}
}
答案 0 :(得分:3)
将male
添加到ButtonGroup
:
错误包含在注释行中:
JRadioButton male = new JRadioButton("male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup bG = new ButtonGroup();
add(male); //this adds the component to the JFrame not the button group
bG.add(female);
可以使用以下方法修复:
bG.add(male);