为什么 Java GUI JFrame 大小在不同的操作系统上大小不同?
Why is Java GUI JFrame size different sizes on different operating systems?
我正在尝试在 Java 上设计 GUI,但我遇到了一个问题,即 JFrame 的大小在不同的操作系统上看起来不同。
您可以在下面看到 GUI 的外观:
在这里你可以看到它在 Linux 上的实际情况:
在这里你可以看到它在 Mac 上的样子:
GUI 的代码是这样的:
private void initialize() {
frmExample = new JFrame();
frmExample.getContentPane().setBackground(Color.BLUE);
frmExample.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 400, 300);
frmExample.getContentPane().add(panel);
frmExample.setTitle("Example");
frmExample.setBounds(100, 100, 400, 272);
frmExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
我尝试将 frmExample.setBounds(100, 100, 400, 272)
更改为 frmExample.setBounds(100, 100, 400, 300)
,这有助于修复此示例项目的颜色,但如果我想在屏幕底部显示文本,这是不可能的GUI 屏幕底部的接缝在所有操作系统上都不相同。
是不是我做错了什么导致了这个问题,或者有什么办法可以解决这个问题?
Is there something I'm doing wrong
frmExample.getContentPane().setLayout(null);
不要使用空布局。 Swing 旨在与布局管理器一起使用,以便组件可以在不同的操作系统上正确显示。
but if I want to have text along the bottom of the screen
那么你的代码应该是这样的:
JPanel panel = new JPanel()
{
@Override
public Dimension getPreferredSize()
{
return new Dimenstion(400, 400);
}
};
frame.add(panel, BorderLayout.CENTER);
JLabel label = new JLabel("text at the bottom of the screen");
frame.add(label, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
现在 pack() 方法将考虑添加到框架的所有组件的首选大小,它在所有平台上看起来都是正确的。
阅读 Using Layout Managers 部分。下载演示代码并使用它来了解如何使用布局管理器的概念。从 BorderLayout 上的演示开始。
我正在尝试在 Java 上设计 GUI,但我遇到了一个问题,即 JFrame 的大小在不同的操作系统上看起来不同。
您可以在下面看到 GUI 的外观:
在这里你可以看到它在 Linux 上的实际情况:
在这里你可以看到它在 Mac 上的样子:
GUI 的代码是这样的:
private void initialize() {
frmExample = new JFrame();
frmExample.getContentPane().setBackground(Color.BLUE);
frmExample.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 400, 300);
frmExample.getContentPane().add(panel);
frmExample.setTitle("Example");
frmExample.setBounds(100, 100, 400, 272);
frmExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
我尝试将 frmExample.setBounds(100, 100, 400, 272)
更改为 frmExample.setBounds(100, 100, 400, 300)
,这有助于修复此示例项目的颜色,但如果我想在屏幕底部显示文本,这是不可能的GUI 屏幕底部的接缝在所有操作系统上都不相同。
是不是我做错了什么导致了这个问题,或者有什么办法可以解决这个问题?
Is there something I'm doing wrong
frmExample.getContentPane().setLayout(null);
不要使用空布局。 Swing 旨在与布局管理器一起使用,以便组件可以在不同的操作系统上正确显示。
but if I want to have text along the bottom of the screen
那么你的代码应该是这样的:
JPanel panel = new JPanel()
{
@Override
public Dimension getPreferredSize()
{
return new Dimenstion(400, 400);
}
};
frame.add(panel, BorderLayout.CENTER);
JLabel label = new JLabel("text at the bottom of the screen");
frame.add(label, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
现在 pack() 方法将考虑添加到框架的所有组件的首选大小,它在所有平台上看起来都是正确的。
阅读 Using Layout Managers 部分。下载演示代码并使用它来了解如何使用布局管理器的概念。从 BorderLayout 上的演示开始。