【问题标题】:CardLayout with Exception on add?CardLayout与添加异常?
【发布时间】:2016-06-18 09:12:32
【问题描述】:

这是我第一次尝试使用 Cardlayout 运行代码。 这是 add 方法的异常(空指针)。 但是我也试图弄清楚如何设计卡片布局,例如卡片,并排或一张在另一张下方。我更喜欢后者。 我已经尝试更改我的代码并阅读有关类似问题的其他主题。如有任何误解,请见谅。

谢谢

     package jnotizen;

     import java.awt.BorderLayout;
     import java.awt.CardLayout;
     import java.awt.event.ItemEvent;
     import java.awt.event.ItemListener;
     import java.awt.image.BufferedImage;
     import java.io.IOException;
     import java.io.InputStream;
     import javax.imageio.ImageIO;
     import javax.swing.*;
     import javax.swing.SwingUtilities;
     import javax.swing.UIManager;

     /**
     *
     * 
     */
     public class JNotizen {

     /**
    * @param args the command line arguments
    */
    JFrame f;
    BorderLayout bl;
    JPanel p;
    JPanel start;
    JPanel notices;
    CardLayout c;
    JTextArea ta;
    JButton nn;
    JButton sv;
    JButton sn;
    String controls = "Controls";
    String noticeBoard = "NoticeBoard";

    public static void main(String[] args) {
    // TODO code application logic here
     SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
     UIManager.put("swing.boldMetal", Boolean.FALSE);
     new JNotizen().startApp();
    }
   }); 

}

private void startApp() {

 c = new CardLayout();
 p = new JPanel(c);

 nn = new JButton("New Notice");
 sv = new JButton("Save Notice");
 sn = new JButton("Search Notice");
 ta = new JTextArea("");

 start.add(nn); // here I get the NullpointerException?
 start.add(sv);
 start.add(sn);

 notices.add(ta);

 p.add(start, controls);
 p.add(notices, noticeBoard);

 CardLayout cl = (CardLayout)(p.getLayout());
 cl.first(p);

 BufferedImage img = null;
 try {
  InputStream inStream =   this.getClass().getClassLoader().getResourceAsStream("iconHash2.jpg");
  img = ImageIO.read(inStream);
 } catch (IOException e) {}
 f = new JFrame();
 f.getContentPane().add(p, BorderLayout.CENTER);
 f.setTitle("NoticeBoard");
 f.setIconImage(img);
 f.setSize(450,550);
 f.setResizable(false);
 f.setVisible(true);
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 }
}

【问题讨论】:

    标签: java cardlayout


    【解决方案1】:

    JPanel start 从未初始化。因此它在 start 变量上调用一个空指针。在添加组件之前尝试初始化JPanel start

    【讨论】:

    • 非常感谢,这是错误。很抱歉没有看到这个。
    猜你喜欢
    • 2016-07-23
    • 2012-05-28
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2011-11-10
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多