package draw;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawTest {
public static void main(String[] args) {
EventQueue.invokeLater(()->
{
JFrame frame = new DrawFrame();
frame.setTitle("DrawTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
A frame that contains a panel with drawings
*/
class DrawFrame extends JFrame{
public DrawFrame() {
add(new DrawComponent());
pack();
}
}
/*
*A component that displays rectangle and ellipses.
*/
class DrawComponent extends JComponent {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
public void painComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double heigh = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX,topY,width,heigh);
g2.draw(rect);
//draw a enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
//draw a diagonal line
g2.draw(new Line2D.Double(leftX,topY,width+leftX,heigh+topY));
//draw a circle with same center
double centerX = rect.getCenterX();
double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY,centerX+radius,centerY+radius);
g2.draw(circle);
}
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
}
}
以上是我的代码,我是从JAVA核心技术那本书上看来的,按理说像这种书一般不会出错。但我对了几遍发现并没有和他不一样的地方,自己也不是很懂,请前辈们指教。为什么图形就是画不出来呢
好吧我自己给自己回答好了。
把paintComponent()改成paint就可以了。
那看你想画的是什么。就是说当paint方法被调用时,paintComponent、paintBorder、 paintChildren 这三个方法也会被按顺序调用,之所以要按这个顺序调用是为了保证子组件能正确地显示在目前这个组件之上。
所以paintComponent就是本身这个容器自己画出自己组件的方法了。如果只是为了改变本身这个容器中的组件,只需要改写paintComponent方法就可以了,如果还要保留容器中的原本组件就别忘了调用super.paintComponent(g)。如果要改写paint方法来改变本身这个容器的组件,那么也别忘了要调用super.paint(g),不然出来的东西是不包含原组件、原边框和子组件的。