1

我正在尝试绘制一个以框架右下角为中心的半径为 60 的圆,以及以框架的上半部分为中心的半径为 50 的正方形。

帧大小为 300 x 300。我一直这样做到现在。

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Test {

    public static void main ( String[] args){

        JFrameTest5 frame = new JFrameTest5();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
         frame.setTitle("Test");


    }
}
class JFrameTest5 extends JFrame {

    public JFrameTest5()
       {
           setLocation(0,0);
           setSize(300,300);

        PanelTest1 panel = new PanelTest1();
     add(panel);        
       }


       }

class PanelTest1 extends JPanel

{

    public void paintComponent(Graphics g) 
    {
        Graphics2D g2 = (Graphics2D)g;

        Ellipse2D circle = new Ellipse2D.Double(250, 225, 120,120);
        g2.draw(circle);

        Rectangle2D rect = new Rectangle2D.Double(75,0,100,100);
        g2.draw(rect);  

    }

}

问题是圆形和矩形似乎不正确,还有其他方法可以设置确切的半径吗?

4

1 回答 1

5

下面的示例包括几个重要的更改:

  • 尽可能使用常量。

  • 使用面板相对几何。

  • 正确使用初始线程

  • 用于pack()调整封闭框架的大小。

代码:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** #see http://stackoverflow.com/a/10255685/230513 */
public class Test {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrameTest frame = new JFrameTest();
            }
        });
    }
}

class JFrameTest extends JFrame {

    public JFrameTest() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Test");
        this.add(new JPanelTest());
        this.pack();
        this.setLocationByPlatform(true);
        this.setVisible(true);
    }
}

class JPanelTest extends JPanel {

    private static final int R = 60;
    private static final int D = 2 * R;
    private static final int W = 50;
    private static final int E = 2 * W;

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(
            getWidth() - D, getHeight() - D, D, D);
        g2.draw(circle);
        Rectangle2D rect = new Rectangle2D.Double(0, 0, E, E);
        g2.draw(rect);
    }
}
于 2012-04-21T02:30:13.107 回答