如何在JFrame上绘制矩形和椭圆

时间:2016-02-10 05:39:09

标签: java jframe rectangles ellipse

我有一个简单的问题要问你。 但我不明白为什么这不会在JFrame上绘制矩形和椭圆。 到目前为止我有JFrame窗口,但只有灰色背景。

请解释谢谢。

FrameViewer.java

import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.FontMetrics;
import java.awt.Font;
import java.awt.BasicStroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Ellipse2D.Double;
import javax.swing.JComponent;

public class ClockComponent extends JComponent{
    Rectangle square;
    Ellipse2D.Double ellipse;

    public void createComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        //create rectangle
        square = new Rectangle(100, 100, 100, 100);
        g2.draw(square);

        //create ellipse
        ellipse = new Ellipse2D.Double(5, 10, 100, 150);
        g2.draw(ellipse);
    }

}

ClockComponent.java

public class AnalogClock {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FrameViewer clock = new FrameViewer();
        clock.createFrame();
    }
}

AnalogClock.java

{{1}}

2 个答案:

答案 0 :(得分:2)

ClockComponent课程中,添加以下内容,而不是createComponent(...)方法:

protected void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    //create rectangle
    square = new Rectangle(100, 100, 100, 100);
    g2.draw(square);

    //create ellipse
    ellipse = new Ellipse2D.Double(5, 10, 100, 150);
    g2.draw(ellipse);
}

答案 1 :(得分:-1)

您可以将课程New扩展为JComponent

,而不是延伸至ClockComponent

则...

您的JApplet班级没有问题

ClockComponent.java :可以扩展到AnalogClock.JavaJApplet override功能。

paint

然后 FrameView.java :文件也应编辑如下

import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.geom.Ellipse2D;
import javax.swing.JApplet;


public class ClockComponent extends JApplet{
    Rectangle square;
    Ellipse2D.Double ellipse;


    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setPaint(Color.BLACK);
        g2.setStroke(new BasicStroke(5.0f));// thickness of the line
        g2.draw(new Ellipse2D.Double(50, 50, 250, 250)); //(x point, y point, width, height)
    }
}

有很多方法可以完成这项任务,这只是绘制2D的一种方法

希望这会对你有所帮助!!