日期:2014-05-20  浏览次数:20912 次

Core Java 2书里的一例题,在我的机子上运行出现了这样的错误
import   java.awt.*;
import   java.awt.event.*;
import   javax.swing.*;
public   class   ButtonTest   {
public   static   void   main(String[]   args){
ButtonFrame   frame=new   ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class   ButtonFrame   extends   JFrame{
public   ButtonFrame(){
setTitle( "ButtonTest ");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
ButtonPanel   panel=new   ButtonPanel();
add(panel);
}
public   static   final   int   DEFAULT_WIDTH=300;
public   static   final   int   DEFAULT_HEIGHT=200;
}
class   ButtonPanel   extends   JPanel{
public   ButtonPanel(){
JButton   yellowButton=new   JButton( "Yellow ");
JButton   blueButton=new   JButton( "Blue ");
JButton   redButton=new   JButton( "Red ");
add(yellowButton);
add(blueButton);
add(redButton);

ColorAction   yellowAction=new   ColorAction(Color.YELLOW);
ColorAction   blueAction=new   ColorAction(Color.BLUE);
ColorAction   redAction=new   ColorAction(Color.RED);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
private   class   ColorAction   implements   ActionListener{
public   ColorAction(Color   c){
backgroundColor=c;
}
public   void   actionPerformed(ActionEvent   event){
setBackground(backgroundColor);
}
private   Color   backgroundColor;
}
}
用javac就能成功编译,但用java运行的时候就会出现在的错误:
Exception   in   thread   "main "   java.lang.Error:   Do   not   use   ButtonFrame.add()   use   But
tonFrame.getContentPane().add()   instead
                at   javax.swing.JFrame.createRootPaneException(JFrame.java:465)
                at   javax.swing.JFrame.addImpl(JFrame.java:491)
                at   java.awt.Container.add(Container.java:307)
                at   ButtonFrame. <init> (ButtonTest.java:16)
                at   ButtonTest.main(ButtonTest.java:6)


------解决方案--------------------
异常
不要用ButtonFrame.add()
用ButtonFrame.getContentPane().add()
------解决方案--------------------
Do not use ButtonFrame.add() use But
tonFrame.getContentPane().add() instead