0
我想用Java創建一個表單,但是我得到了一個NullPointerException
。這是我的代碼:GridLayout的問題
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Inscripcion extends JFrame implements ActionListener {
JLabel Nombre;
JLabel Sexo;
JTextField CampoTexto;
JRadioButton M;
JRadioButton F;
ButtonGroup Casillas;
JButton Aceptar;
JPanel A;
JPanel B;
JPanel C;
Inscripcion() {
super("Formulario de Inscripción.");
Container Contenedor = getContentPane();
Contenedor.setLayout(new FlowLayout());
Nombre = new JLabel("Nombre: ");
Contenedor.add(Nombre);
CampoTexto = new JTextField(20);
Contenedor.add(CampoTexto);
A = new JPanel();
A.setLayout(new GridLayout(2, 1));
Contenedor.add(A, BorderLayout.NORTH);
Sexo = new JLabel("Sexo: ");
Contenedor.add(Sexo);
M = new JRadioButton("M", false);
M.addActionListener(this);
Contenedor.add(M);
F = new JRadioButton("F", false);
F.addActionListener(this);
Contenedor.add(F);
B.setLayout(new GridLayout(3, 1));
Contenedor.add(B, BorderLayout.CENTER);
Aceptar = new JButton("Aceptar");
Aceptar.addActionListener(this);
B.setLayout(new GridLayout(3, 1));
Contenedor.add(B, BorderLayout.SOUTH);
Contenedor.add(Aceptar, BorderLayout.CENTER);
setSize(300, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent Evento) {
String Nom = CampoTexto.getText();
String Sex = M.isSelected() ? "Masculino":"Femenino";
System.out.println(Nom + Sex + " ");
}
public static void main(String[] Flogging) {
Inscripcion obj = new Inscripcion();
obj.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
唯一的例外出現在該行:提前
B.setLayout(new GridLayout(3, 1));
感謝。
我預見了將來使用調試器的一課;)。我也預見你會閱讀[Java編程語言的代碼約定](http://www.oracle.com/technetwork/java/codeconv-138413.html)(又名如何贏得朋友並影響他人;)) – MadProgrammer 2013-02-21 03:19:30