在这里,我在这里尝试构建简单的CardLayout,但是它在第19行和第26行抛出NullPointerException。这是代码。我试图仅显示给定2面板中名为panel1的第一个面板,这些面板被间接添加到主controlPanel中。我是Java Swing GUI编程的初学者。请帮我解决这个问题。
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.awt.event.*;
import javax.swing.*;
public class test {
private JFrame mainFrame;
private JLabel label1 = new JLabel("This is Label 1");
private JLabel label2 = new JLabel("This is Label 2");
private JPanel controlPanel;
private JPanel panel1;
private JPanel panel2;
public static void main(String[] args){
test coutex = new test();
coutex.prepareGUI();
}
public void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
CardLayout cout = new CardLayout();
controlPanel.setLayout(cout);
panel1.add(label1);
panel2.add(label2);
panel1.setBackground(Color.BLUE);
panel2.setBackground(Color.RED);
controlPanel.add(panel1,"1");
controlPanel.add(panel2,"2");
cout.show(controlPanel,"1");
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
}
最佳答案
问题在这里:
controlPanel.setLayout(cout);
controlPanel
对象从未初始化,因此您尝试在null对象上调用方法。首先将其设置为new JPanel()
。此外,您永远不会初始化
panel1
或panel2
。同样的建议适用。