Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Swing:图形未在单独的JPanel中居中_Java_Swing_Jpanel_Drawing_Geometry - Fatal编程技术网

Java Swing:图形未在单独的JPanel中居中

Java Swing:图形未在单独的JPanel中居中,java,swing,jpanel,drawing,geometry,Java,Swing,Jpanel,Drawing,Geometry,我是Jari,在一个单独的JPanel中画一个圆有点困难: 我的圆圈不会在JPAND中间称为“jPANELL输出”,这里是我的代码: Graphics2D graphics = (Graphics2D) jPanelOutput.getGraphics().create(); Insets insets = jPanelOutput.getInsets(); System.out.println(insets.toString()); int w = (int)((jP

我是Jari,在一个单独的JPanel中画一个圆有点困难: 我的圆圈不会在JPAND中间称为“jPANELL输出”,这里是我的代码:

Graphics2D graphics = (Graphics2D) jPanelOutput.getGraphics().create();

    Insets insets = jPanelOutput.getInsets();
    System.out.println(insets.toString());
    int w = (int)((jPanelOutput.getWidth())/ 2)-insets.left-insets.right;
    int h = (int)(jPanelOutput.getHeight()/ 2)-insets.top-insets.bottom;
    System.out.println(w + "  " + h);
    graphics.translate(w, h);
    graphics.drawRect(0, 0, 1, 1);
    graphics.drawOval(0, 0, 150, 150);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setColor(Color.BLACK);

    graphics.dispose();
但结果是: 不用担心拼写,它是荷兰语(“vlakke spiegel”的意思是平面镜,“cirkel”的意思是圆。标题的意思是fysics mirror laws

提前谢谢
Jari

问题是圆是从左上角画出来的。圆的左上角位于完美的中心位置。您需要做的就是从中心点减去圆的宽度和高度。
以下代码将使圆居中

int cw = 150;
int ch = 150;
graphics.translate(w - cw / 2, h - ch / 2);
graphics.drawRect(0, 0, 1, 1);
graphics.drawOval(0, 0, cw, ch);

在这里搜索getPreferredSIze,然后所有坐标都来自getHeight/Weight,小心地使用Swap Height/Weight v.s.Weight/Height,因为,看起来就像是您的打印屏幕在谈论的……为了更好地帮助您,请尽早发布SSCCE/MCVE、short、runnable、Compileable不要
getGraphics()
。“Swing程序应覆盖
paintComponent()
…”--。