有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何绘制具有指定半径的圆形和矩形?

我试图画一个半径为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);  

    }

}

问题是圆和矩形似乎不正确,是否有其他方法来设置精确的半径


共 (1) 个答案

  1. # 1 楼答案

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

    • 尽可能使用常量

    • 使用面板相对几何图形

    • 正确使用initial threads

    • 使用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);
        }
    }