日期:2014-05-20  浏览次数:20785 次

想创建一个有各种部件的窗口,一直没看出问题,可总出错,请哪位高手指点一下。。。
想创建一个有各种部件的窗口,一直没看出问题,可总出错,请哪位高手指点一下。。。
import java.awt.*;
import javax.swing.*;

public class Printer extends JFrame {

private JPanel panel1,panel2,panel3,panel4,panel5,panel6 = new JPanel();
private JTextArea area1,area2,area3 = new JTextArea();
private JComboBox box;
private JCheckBox box1,box2,box3,box4;
private JLabel label1,label2;
private JButton but1,but2,but3,but4;
private JRadioButton rBut1,rBut2,rBut3;
private Container container;
private String s[] = {"High","Low","Me","You","He","She"};
private ButtonGroup radioGroup = new ButtonGroup();

public Printer() {

container = getContentPane();
container.setLayout(new FlowLayout() );

label1 = new JLabel("Printer: MyPrinter");
label2 = new JLabel("Print Qualit");
but1 = new JButton("Ok");
but2 = new JButton("Cancel");
but3 = new JButton("Setup");
but4 = new JButton("Help");
box = new JComboBox(s);
box1 = new JCheckBox("Print to File");
box2 = new JCheckBox("Image");
box3 = new JCheckBox("Text");
box4 = new JCheckBox("Code");
rBut1 = new JRadioButton("Selection",true);
rBut2 = new JRadioButton("All",false);
rBut3 = new JRadioButton("Applet",false);
radioGroup.add(rBut1);
radioGroup.add(rBut2);
radioGroup.add(rBut3);

box.setMaximumRowCount(3);

panel1.setLayout(new FlowLayout() ); //panel3的center
panel2.setLayout(new GridLayout(1,3) );
panel4.setLayout(new GridLayout(3,1) );
panel5.setLayout(new GridLayout(3,1) );
panel5.setLayout(new GridLayout(3,1) );

//四个JButton
panel6.add(but1);
panel6.add(but2);
panel6.add(but3);
panel6.add(but4);

//三个JRadioBox
panel5.add(rBut1);
panel5.add(rBut1);
panel5.add(rBut1);

//三个JCheckBox
panel4.add(box2);
panel4.add(box3);
panel4.add(box4);

//panel3的center
panel1.add(panel4);
panel1.add(area2);
panel1.add(panel5);

//panel3的SOUTH
panel2.add(label2);
panel2.add(box);
panel2.add(box1);

panel3.add(label1,BorderLayout.NORTH);
panel3.add(panel2,BorderLayout.SOUTH);
panel3.add(panel1,BorderLayout.CENTER);
panel3.add(area1,BorderLayout.WEST);
panel3.add(area3,BorderLayout.EAST);

container.add(panel3);
container.add(panel6);

setLocation(300,300);
setSize(300,300);
setVisible(true);
}

public static void main(String[] args) {
Printer application = new Printer();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

以下是eclipse指出的错误:
Exception in thread "main" java.lang.NullPointerException
at Printer.<init>(Printer.java:43)
at Printer.main(Printer.java:90)

------解决方案--------------------
private JPanel panel1,panel2,panel3,panel4,panel5,panel6 = new JPanel();
private JTextArea area1,area2,area3 = new JTextArea();

这两句话想偷懒是不行的,这样只有最后一个被初始化了。

所以老老实实每个都new 吧。