当前位置: 代码迷 >> Java相关 >> swing编程问题,求助
  详细解决方案

swing编程问题,求助

热度:324   发布时间:2008-02-05 14:31:27.0
swing编程问题,求助
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class JButtonDemo {
    private JFrame jframe;
    private JPanel jpl;
    private ButtonGroup bg;
    private JButton jb1,jb2,jb3;

    public JButtonDemo() {
        jframe = new JFrame("按钮演示窗口");
        bg = new ButtonGroup();
        jpl.setBorder(new TitledBorder("按钮演示组"));

        jb1 = new JButton("按钮1【含有图片的按钮】",new ImageIcon("gif001.gif"));
        jb1.setHorizontalTextPosition(JButton.CENTER);
        jb1.setVerticalTextPosition(JButton.BOTTOM);

        jb2 = new JButton("按钮2【可变换图片的按钮】");
        Icon general = new ImageIcon("gif002.gif");
        Icon press = new ImageIcon("gif003.gif");
        Icon rollover = new ImageIcon("gif004.gif");
        jb2.setRolloverEnabled(true);
        jb2.setIcon(general);
        jb2.setRolloverIcon(rollover);
        jb2.setPressedIcon(press);
        jb2.setHorizontalTextPosition(JButton.CENTER);
        jb2.setVerticalTextPosition(JButton.BOTTOM);

        jb3 = new JButton("默认按钮2【A】");
        jb2.setMnemonic('a');
        jframe.getRootPane().setDefaultButton(jb3);
        jb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(jframe,"这是按钮3,快捷键(Alt+a)");
            }
        });

        bg.add(jb1);
        bg.add(jb2);
        bg.add(jb3);

        jpl.add(jb1);
        jpl.add(jb2);
        jpl.add(jb3);

        jframe.getContentPane().add(jpl);
        jframe.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        jframe.pack();
        jframe.setVisible(true);
    }
    public static void main(String[] args)
    {
        new JButtonDemo();
    }
}
程序编译通过,运行时报错,信息为
Exception in thread "main" java.lang.NullPointerException
        at JButtonDemo.<init>(JButtonDemo.java:15)
        at JButtonDemo.main(JButtonDemo.java:60)
Press any key to continue...
是什么原因啊?
搜索更多相关的解决方案: swing  import  new  private  

----------------解决方案--------------------------------------------------------
jpl.setBorder(new TitledBorder("按钮演示组"));
这里当然有问题啦,你有没初始化jp1就调用它的方法,所以出现空指针异常
----------------解决方案--------------------------------------------------------
少了一条
jpl = new JPanel();
----------------解决方案--------------------------------------------------------