想做一个自动选号的小东西。
但是在做界面的时候,有问题,编译过了,但是一运行就提示错误
java.lang.NullPointerException
at LotteryDrawing.addComponent(LotteryDrawing.java:53)
at LotteryDrawing.<init>(LotteryDrawing.java:42)
at LotteryDrawing.main(LotteryDrawing.java:57)
Exception in thread "main"
Java Result: 1
我用的是NetBeans
下边是我的代码,希望有明白的人指点一下。谢谢~
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LotteryDrawing extends JFrame{
JTextField NumText;
JTextField ChoiceText;
JTextField ResultText;
JButton BtnResult;
JLabel NumLbl;
JLabel ChoiceLbl;
JLabel ResultLbl;
GridBagLayout mainframe;
GridBagConstraints gbc;
JPanel container;
public LotteryDrawing (String title){
super(title);
//设置容器布局
Container mainframe = getContentPane();
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
mainframe.add(container);
//创建辅助类
gbc = new GridBagConstraints();
//初始化标签。
NumLbl = new JLabel("Number you need draw");
ChoiceLbl = new JLabel("Nuber you can draw");
ResultLbl = new JLabel("Result");
//初始化文本域。
NumText = new JTextField("Enter the number.");
ChoiceText = new JTextField("Enter the number.");
ResultText = new JTextField();
//初始化按钮
BtnResult = new JButton("Result");
//相容器内添加组件
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(NumLbl,0,0,1,1);
}
public void addComponent(Component c,int row,int col,int nrow,int ncol){
gbc.gridx = col;
gbc.gridy = row;
gbc.gridwidth = ncol;
gbc.gridheight = nrow;
mainframe.setConstraints(c,gbc);
add(c);
}
public static void main(String[] args){
LotteryDrawing appLottery = new LotteryDrawing("彩票中奖率");
appLottery.setSize(300,200);
appLottery.setVisible(true);
appLottery.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
关于gridbag网格包布局的问题