GridLayout有问题

时间:2013-02-21 03:10:40

标签: java swing nullpointerexception radio-button grid-layout

我正在尝试使用Java创建表单,但我得到了NullPointerException。这是我的代码:

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

提前致谢。

1 个答案:

答案 0 :(得分:3)

B永远不会被初始化...在发布此类问题之前,请考虑审核您的代码。