Graphics2D对象调用draw方法但无法显示图像
import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
public class SimpleFrameTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable(){
public void run()
{
JFrame frame = new DrawFrame();
frame.setTitle("画图测试");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
add(new DrawComponent());
pack();
}
}
class DrawComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 1200;
private static final int DEFAULT_HEIGHT = 800;
public void paintCpmponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,height);
g2.draw(rect);
}
public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
}
}
1.按照书上的例子应该是会显示一个矩形的,但是实际上内容窗口并没有内容。
2.另外我还想问一下,为什么 DrawComponent 类只是写了这两个方法,也并没有在构造器中调用,但是实际上也调用了,是和frame.add这个方法有关系吗。