我刚刚学javaSwing 写了这个测试代码,一运行就报错,那位大虾给解解围》

package qiao;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javaSwing5.Test_8;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class text_08 extends JFrame{
private JPanel panel = null;
private JPanel p = null;
private CardLayout card= null;
private JButton button_1 = null;
private JButton button_2 = null;
private JButton b_1=null;
private JButton b_2=null;
private JButton b_3=null;

private JPanel p_1=null;
private JPanel p_2=null;
private JPanel p_3=null;

public text_08(){
super("CardLayout Test");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
card = new CardLayout(5,5);
panel = new JPanel(card);
p=new JPanel();
button_1 = new JButton("上一页");
button_2 = new JButton("下一步");
b_1=new JButton("1");
b_2=new JButton("2");
b_3=new JButton("3");
b_1.setMargin(new Insets(2, 2, 2, 2));
b_2.setMargin(new Insets(2, 2, 2, 2));
b_3.setMargin(new Insets(2, 2, 2, 2));
p.add(button_1);
p.add(b_1);
p.add(b_2);
p.add(b_3);
p.add(button_2);
p_1.setBackground(Color.RED);
p_2.setBackground(Color.BLUE);
p_3.setBackground(Color.GREEN);
p_1.add(new JLabel("第一页"));
p_1.add(new JLabel("第二页"));
p_1.add(new JLabel("第三页"));
panel.add(p_1,"p1");
panel.add(p_2,"p2");
panel.add(p_3,"p3");
button_1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
card.previous(panel);
}
});
button_2.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
card.next(panel);
}
});
b_1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
card.show(panel, "p1");
}
});
b_2.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
card.show(panel, "p2");
}
});
b_3.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
card.show(panel, "p3");
}
});
this.getContentPane().add(panel);
this.getContentPane().add(p,BorderLayout.SOUTH);
this.setSize(300,200);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new text_08();
}
}

p_1
p_2
p_3
没有初始化
在构造方法中加入
p_1 = new JPanel();
p_2 = new JPanel();
p_3 = new JPanel();
就可以了
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-01-06
把错发出来!!!
第2个回答  2011-01-06
其他的错误暂且不说,
你这里先要改p_1, p_2,p_3都没有初始化,肯定有nullpointerException吧
改成
private JPanel p_1 = new JPanel();
private JPanel p_2 = new JPanel();
private JPanel p_3 = new JPanel();
相似回答