Java Swing:绘图未在单独的 JPanel 中居中
Java Swing: drawing not centered in separate JPanel
我是 Jari,我在单独的 JPanel 中画圆时遇到了一些问题:
我的圈子不会位于名为 "jPanelOutput" 的 jpanel 中间,这是我的代码:
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" 表示圆。标题表示物理学镜像定律。
提前致谢
贾里
问题是圆是从 top_left 角绘制的。圆圈的左上角位于完美的中心位置。您需要做的就是从中心点减去圆的宽度和高度。
下面的代码将圆圈居中。
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);
我是 Jari,我在单独的 JPanel 中画圆时遇到了一些问题: 我的圈子不会位于名为 "jPanelOutput" 的 jpanel 中间,这是我的代码:
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();
但是输出是:
提前致谢 贾里
问题是圆是从 top_left 角绘制的。圆圈的左上角位于完美的中心位置。您需要做的就是从中心点减去圆的宽度和高度。
下面的代码将圆圈居中。
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);