所以我試圖創建3個面板。第一個面板具有佈局設置(例如單選按鈕和下一個按鈕),現在我添加兩個具有不同背景色的新面板。但是當我執行代碼時,我得到一個空點異常的錯誤。我如何解決這個問題?爲什麼GUI不能正常工作,代碼是否正確?
下面是代碼:
import java.awt.Color;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.CardLayout;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
private JPanel panelFirst;
private JPanel panelSecond;
CardLayout c1 = new CardLayout();
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
panel.setLayout(c1);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panel.add(panelFirst,"1");
panel.add(panelSecond,"2");
c1.show(panel,"panel");
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
btNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
c1.show(panel, "2");
}
});
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup();
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
告訴我們的空指針異常情況發生。哪條線。編輯您的問題以獲得異常的完整堆棧跟蹤。 –
「*我得到零點異常的錯誤*」 ==>張貼堆棧跟蹤,其中包含爲例外出現的確切的行... – assylias
這兩條線將拋出一個NPE:'panelFirst.setBackground(顏色。藍色); panelSecond.setBackground(Color.GREEN);'因爲沒有這些面板已經被實例化... – assylias