import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.UIManager;public class ArrayBound extends JFrame{ GridBagLayout layout;
GridBagConstraints constraints;
Container container;
JFormattedTextField f;
JTextArea area;
String []s = {"50元奖金","唱一首歌","学狗叫","为大家讲一个笑话","3万元奖金"};

public ArrayBound(){
JLabel label1 = new JLabel("聚会趣味题:");
JLabel label2 = new JLabel("题目编号:");
JButton b = new JButton("确定");
f = new JFormattedTextField();
area = new JTextArea();

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_Listener(e);
}
});

layout = new GridBagLayout();
constraints = new GridBagConstraints();

constraints.fill = GridBagConstraints.BOTH;
addComponent(label1,0,0,3,1);
addComponent(label2,1,0,1,1);
addComponent(f,1,2,1,1);
addComponent(b,1,3,1,1);
addComponent(area,2,0,3,1);

container = getContentPane();
container.setLayout(layout);

setTitle("jFormattedTextField");
setBounds(300,300,300,300);
setVisible(true);
}

public void addComponent(Component component,int row,int column,int width,int height){
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
container.add(component);
}

public void do_Listener(ActionEvent e){
int index = ((Number)f.getValue()).intValue();
try{
area.setText(s[index]);
}catch(Exception e2){
area.setText("发生异常: \n" + e2.toString());
}
}

public static void main(String[]args){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}catch(Throwable e){
e.printStackTrace();
}
ArrayBound application = new ArrayBound();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}
抛出java.lang.NullPointerException异常
在标红的地方
高手帮忙看看啊,在线等....

解决方案 »

  1.   

    container = getContentPane();
    container.setLayout(layout);
    这两句放在前面。
    比如:layout = new GridBagLayout();
    constraints = new GridBagConstraints();container = getContentPane();//前移这。
    container.setLayout(layout);constraints.fill = GridBagConstraints.BOTH;
    addComponent(label1,0,0,3,1);
    addComponent(label2,1,0,1,1);
    addComponent(f,1,2,1,1);
    addComponent(b,1,3,1,1);
    addComponent(area,2,0,3,1);但运行出窗口后,时还有异常。楼主再调试下。