【发布时间】:2019-09-25 16:26:18
【问题描述】:
当我在 JFrame 内的 JPanel 上绘制 [drawRect(x, y, width, height)] 一个矩形时,其宽度为500,它实际上比我屏幕上的 500 像素宽。这是如何测量的?
虽然在 JPanel 上绘制矩形和围绕它的 JFrame 的大小搞砸了,但我认识到,当涉及到 JFrame 和 JPanel 时,500“宽度”是不同的东西。 创建的宽度为 1920 像素的 JFrame 的宽度正好是 1920 像素,也就是说,与我的屏幕 (1920x1080) 一样宽。 如果我在 JFrame 内的 JPanel 上绘制一个宽度为 1920 的矩形,它会将我的屏幕恰好扩展 385 个像素。分别:与我的屏幕一样宽的绘制矩形需要 1535 的宽度。
import javax.swing.*;
import java.awt.*
public class Main {
public static void main(String[] args){
JFrame window = new JFrame();
window.setSize(1920,1080); //Window as wide as the screen
window.add(new Canvas());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
public class Canvas extends JPanel {
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(0, 0, 1920, 500); //Paints a rectangle on the JPanel
}
}
打开的窗口与我的屏幕一样宽,但里面的矩形扩展了它。
如果我将矩形的宽度更改为 1535 [drawRect(0, 0, 1535, 500)],它与 JFrame/screen 一样宽。这是为什么呢?
编辑:由于 Windows 10 Frame 的侧面没有装饰,只有顶部的标准菜单栏,我认为这不是问题(据我了解装饰)。
【问题讨论】:
-
我现在不能测试,但是你打电话给
super.paintComponentS(g);而不是super.paintComponent(g);(注意S)。 -
@Frakcool 谢谢!那是笔误,我更正了。但是对于这个问题,它没有任何区别。
-
区别在于框架装饰。见stackoverflow.com/a/57042907/11595728
-
@SDJ 我已经阅读了有关装饰品的信息(我完全相信这篇文章)。但是 Windows 10 框架的侧面没有任何装饰。
-
我会运行帖子中的代码来确定。在我的win10盒子上,边框左右各有8个像素的边框装饰(共16个)。用肉眼可能很难看到,但它们肯定存在。