我遇到了 JFrame 大小的问题:
我想在 Jframe 中显示内容。内容的大小为 640 x 480。但是我不能使用方法 JFrame.setSize(640, 480);
因为我还想显示窗口的装饰。
我的第一个想法是:添加一个具有首选尺寸的面板,然后使用 pack();。但这也不起作用 - 我只得到一个非常小的窗口。
我认为我的问题的解决方案可能与此类似:
这是我的代码:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Fenster extends JFrame {
JPanel panel;
Dimension dim;
Fenster(){
dim = new Dimension(640, 480);
panel = new JPanel();
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
panel.setBounds(0, 0, 640, 480);
panel.setDoubleBuffered(true);
JLabel label = new JLabel("bla");
panel.add(label);
this.setLayout(null);
this.getContentPane().add(panel);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
最佳答案
this.setLayout(null);
是你的问题。让布局管理器完成它的工作
来自JavaDocs
public void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.
If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.
大多数容器(JComponent
、JPanel
)都有默认的首选大小0x0
,布局管理器根据要求提供此信息布局管理器本身和容器的内容,但使用 null
,您可以有效地使容器 0x0
...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new JLabel("Look ma, no null layouts!"));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
}
}
避免使用 null
布局,像素完美布局是现代 UI 设计中的一种幻觉。影响组件个体尺寸的因素太多,您无法控制其中任何一个。 Swing 的设计初衷是与布局管理器一起工作,放弃它们将导致无穷无尽的问题,您将花费越来越多的时间来尝试纠正
参见Why is it frowned upon to use a null layout in SWING?了解更多详情...
关于Java - 设置装饰 JFrame 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769406/