问一个java问题,下面代码为什么会报java.lang.IllegalArgumentException 这种异常哪 希望大神详细解答
import javax.swing.* ;
public class DrawCircle extends JFrame {
private final int OVAL_WIDTH = 80 ;
private final int OVAL_HEIGHT = 80 ;
public DrawCircle(){
super();
initialize();
}
private void initialize (){
this.setSize(300,200) ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new DrawPanel());
this.setTitle("奥运五环");
//this.setVisible(true);
}
public static void main(String[]args){
new DrawCircle().setVisible(true);
}
private class DrawPanel extends JFrame{
public void paint(Graphics g){
super.paint(g);
g.drawOval(10, 10, OVAL_WIDTH ,OVAL_HEIGHT );
g.drawOval(80, 10, OVAL_WIDTH ,OVAL_HEIGHT );
g.drawOval(150, 10, OVAL_WIDTH ,OVAL_HEIGHT );
g.drawOval(50, 70, OVAL_WIDTH ,OVAL_HEIGHT );
g.drawOval(120, 70, OVAL_WIDTH ,OVAL_HEIGHT );
}
}
} 展开
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:431)
at java.awt.Container.addImpl(Container.java:1039)
at javax.swing.JLayeredPane.addImpl(JLayeredPane.java:212)
at java.awt.Container.add(Container.java:927)
at javax.swing.JRootPane.setContentPane(JRootPane.java:608)
at javax.swing.JFrame.setContentPane(JFrame.java:671)
at DrawCircle.initialize(DrawCircle.java:18)
at DrawCircle.<init>(DrawCircle.java:11)
at DrawCircle.main(DrawCircle.java:24)
你为什么会设置contentPane为一个JFrame呢?
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawCircle extends JFrame {
private final int OVAL_WIDTH = 80;
private final int OVAL_HEIGHT = 80;
public DrawCircle() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new DrawPanel());
this.setTitle("奥运五环");
// this.setVisible(true);
}
public static void main(String[] args) {
new DrawCircle().setVisible(true);
}
private class DrawPanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
g.drawOval(10, 10, OVAL_WIDTH, OVAL_HEIGHT);
g.drawOval(80, 10, OVAL_WIDTH, OVAL_HEIGHT);
g.drawOval(150, 10, OVAL_WIDTH, OVAL_HEIGHT);
g.drawOval(50, 70, OVAL_WIDTH, OVAL_HEIGHT);
g.drawOval(120, 70, OVAL_WIDTH, OVAL_HEIGHT);
}
}
}
关于setContentPane()和getContentPane()的应用
------摘要:java_流子 Fab.19 2006--------
我们可以在 JFrame 对象中添加 AWT 或者 Swing 组件。但是,虽然它有 add 方法,却不能直接用于添加组件,否则会抛出异常——不信就试试。造成这个现象的原因只有一个解释:JFrame 不是一个容器,它只是一个框架。那么,应该怎么添加组件呢?
JFrame 有一个 Content Pane,窗口能显示的所有组件都是添加在这个 Content Pane 中。JFrame 提供了两个方法:getContentPane 和 setContentPane 就是用于获取和设置其 Content Pane 的。
对JFrame添加组件有两种方式:
1)用getContentPane()方法获得JFrame的内容面板,再对其加入组件:frame.getContentPane().add(childComponent)
2)建立一个Jpanel或JDesktopPane之类的中间容器,把组件添加到容器中,用setContentPane()方法把该容器置为JFrame的内容面板:
JpanelcontentPane=newJpanel();
……//把其它组件添加到Jpanel中;
frame.setContentPane(contentPane);
//把contentPane对象设置成为frame的内容面板