首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

Core Java 2书里的一例题,在小弟我的机子上运行出现了这样的异常

2012-01-06 
Core Java 2书里的一例题,在我的机子上运行出现了这样的错误importjava.awt.*importjava.awt.event.*imp

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

热点排行