[英]Why doesn't my button position properly on my JFrame no layout?
So I've got a JFrame which uses setLayout(null)
so I can position my elements by hand. 因此,我有一个使用
setLayout(null)
的JFrame,以便可以手动setLayout(null)
元素。
However, when accessing the content pane and getting the size for the frame, it says its height is 1.0. 但是,当访问内容窗格并获取框架的大小时,它表示其高度为1.0。
Does anyone know how I can fix this? 有谁知道我该如何解决?
Here is the code: 这是代码:
import javax.swing.*;
import java.awt.*;
public class Launcher extends JFrame
{
public Launcher(String title) {
super(title);
setLayout(null);
pack();
setSize(new Dimension(LauncherUtil.LAUNCHER_WIDTH, LauncherUtil.LAUNCHER_HEIGHT));
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
displayComponents();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Launcher launch = new Launcher(LauncherUtil.LAUNCHER_TITLE);
launch.setVisible(true);
}
});
}
private void displayComponents() {
Dimension size = getContentPane().getSize();
JButton launchButton = new JButton("Launch Game");
System.out.println(size.getHeight());
launchButton.setBounds(0, (int)size.getHeight() - 60, (int)size.getWidth(), 60);
add(launchButton);
}
}
may be if you try to get the screen size by using Toolkit would be work like you want 可能是如果您尝试通过使用工具包来获取屏幕尺寸,则可能会如您所愿
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
it brings you the screen size where java program is running. 它带给您运行Java程序的屏幕尺寸。 Hope it helps.
希望能帮助到你。
The content pane is a JPanel
whose default size is 1x1px. 内容窗格是一个
JPanel
其默认大小为1x1px。 Since you did not put any components into the content pane and have not set a preferred size for the panel, the content pane's size remains 1x1px. 由于您没有在内容窗格中放置任何组件,也没有为面板设置首选大小,因此内容窗格的大小仍为1x1px。
One way to fix this is to call these three methods in the following order: 解决此问题的一种方法是按以下顺序调用这三种方法:
setLayout(null);
setPreferredSize(new Dimension(300, 400));
pack();
However, you should be using a layout manager instead of managing the size and position of your components by hand. 但是,您应该使用布局管理器,而不是手动管理组件的大小和位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.