山城SC 2017-11-03 05:46 采纳率: 0%
浏览 1680
已结题

图形画不出来(java)

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核心技术那本书上看来的,按理说像这种书一般不会出错。但我对了几遍发现并没有和他不一样的地方,自己也不是很懂,请前辈们指教。为什么图形就是画不出来呢

  • 写回答

2条回答 默认 最新

  • 山城SC 2017-11-03 05:50
    关注

    好吧我自己给自己回答好了。
    把paintComponent()改成paint就可以了。

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?