2016-06-18 5 views
0

私はCardlayoutでコードを実行しようとしました。 addメソッドでは例外(nullpointer)です。 しかし、私はまた、カードレイアウトをどのように設計するかを理解しようとしました。カードを横に並べて配置するか、上下に配置します。私は後者を好む。 私は既にコードを変更して、同様の問題に関する他のトピックを読んでみました。何か誤解をおかけして申し訳ありません。 追加時に例外が発生したCardLayout?

JPanel startが初期化されなかったあなた

 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); 

} 
} 

答えて

1

ありがとうございます。したがって、開始変数にヌルポインタを呼び出しています。コンポーネントを追加する前にJPanel startを初期化してください。

+0

ありがとうございました。エラーでした。これを見ないとすみません。 –

関連する問題