当我在JFrame内的JPanel上绘制[drawRect(x, y, width, height)
]矩形时,其宽度为500,实际上比我屏幕上的500像素宽。如何测量?
虽然我在JPanel上四处绘制矩形和周围的JFrame大小,但我认识到,当涉及到JFrame和JPanel时,500个“宽度”是不同的东西。 创建的宽度为1920像素的JFrame恰好是1920像素宽,也就是说,与我的屏幕(1920x1080)一样宽。 如果我在JPanel上(即JFrame内)绘制一个宽度为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 /屏幕一样。为什么会这样?
编辑:由于Windows 10框架的侧面没有装饰,只有顶部的标准菜单栏,所以我认为这不是问题所在(据我了解装饰)。
答案 0 :(得分:1)
简短答案:是的。
说明:让我们深入了解!
在MacOS上运行Java Swing(已通过Metal LAF测试),JFrame的左右两侧为零。这类似于Windows 10上某些主题的渲染。内容窗格和面板的填充矩形之间的间隙应保持8像素。程序运行时,调整大小,然后检查一下。如果这不是您遇到的行为,请随时发表评论。
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
final String name;
name = javax.swing.plaf.metal.MetalLookAndFeel.class.getName();
try {
UIManager.setLookAndFeel(name);
}
catch (Throwable e) {
e.printStackTrace();
}
createAndShowWindow();
});
}
private static void createAndShowWindow() {
final int width = 1920;
final int height = 800;
final int padding = 8;
JFrame window = new JFrame();
window.setTitle("Hello World.");
window.setPreferredSize(new Dimension(width, height));
window.setSize(width, height); //Window as wide as the screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new Canvas(padding);
window.add(canvas, BorderLayout.CENTER);
window.pack();
window.setVisible(true);
System.out.println("w: " + window.getSize());
System.out.println("c: " + window.getContentPane().getSize());
System.out.println("p: " + canvas.getSize());
System.out.println("i: " + window.getInsets());
}
public static class Canvas extends JPanel {
private final int padding;
public Canvas(int padding) {
this.padding = padding;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(180, 120, 16));
//Paints a rectangle on the JPanel
int x = padding;
int y = padding;
int w = getWidth() - 2 * padding;
int h = getHeight() - 2 * padding;
g.fillRect(x, y, w, h);
}
}