如何手动设置 JComponents 等的位置

How to manually set locations of JComponents etc

我已经通过将 JFrame 的布局设置为 null 来尝试 setLocation(x,y) 和 setLocationRelativeTo(null) 但这没有用 out.While 搜索我发现这个问题已经被两三个人问过了但他们已经通过 setLocation() 和 setLocationRelativeTo(null) 完成了。

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;

public class StartMenu{
    JPanel startPanel;
    JLabel title;
    JButton startTest;
    JButton exit;
    JFrame menuFrame;

    public StartMenu(){
        menuFrame = new JFrame("Start Menu");
        menuFrame.setLayout(null);

        startPanel = new JPanel();

        title = new JLabel("Adaptive Test",JLabel.CENTER);
        title.setLocation(20,20);
        startPanel.add(title);

        startTest = new JButton("Start");
        startTest.setLocation(40,40);
        startPanel.add(startTest);

        exit = new JButton("Exit");
        exit.setLocation(100,100);
        startPanel.add(exit);
        menuFrame.setContentPane(startPanel);

        menuFrame.setVisible(true);
        menuFrame.setSize(500, 500);
        menuFrame.setResizable(false);
        menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

您的 JFrame 的布局设置为空,但 startPanel 的布局不是。所以首先,使用:

startPanel.setLayout(null);

现在,使用 component.setBounds(x, y, width, height) 而不是 component.setLocation(x, y),因此您还为它们设置了大小。

但正如评论中所说,最好使用 layout managers 而不是空布局。

首先你将 JFrame 设置为 null 而不是 JPanel,所以你必须使用

startPanel.setLayout(null);

那么您应该使用 setBounds 而不是 setLocation,因为如果您只是使用空布局管理器设置位置,您可能在面板上看不到任何内容,因为默认情况下所有维度都初始化为 0。

所以,您可以像这样重写您的软件:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class StartMenu{
    JPanel startPanel;
    JLabel title;
    JButton startTest;
    JButton exit;
    JFrame menuFrame;

    public StartMenu(){
        menuFrame = new JFrame("Start Menu");
        menuFrame.setLayout(null);

        startPanel = new JPanel();
        startPanel.setLayout(null);

        title = new JLabel("Adaptive Test",JLabel.CENTER);
        title.setBounds(20,20, 100, 30);
        startPanel.add(title);

        startTest = new JButton("Start");
        startTest.setBounds(50,50, 100, 30);
        startPanel.add(startTest);

        exit = new JButton("Exit");
        exit.setBounds(100,100, 100 ,30);
        startPanel.add(exit);
        menuFrame.setContentPane(startPanel);

        menuFrame.setVisible(true);
        menuFrame.setSize(500, 500);
        menuFrame.setResizable(false);
        menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

像这样你可以得到一些东西,但是手动设置软件中的所有位置和大小并不是一个很好的编程习惯,因为它在不同的系统上不能很好地工作(因此它不能移植)当您的软件开始增加数十甚至数百个图形元素时,您还会发现自己陷入了调试噩梦。

我的建议是使用 gridBagLayout,一开始我觉得很晦涩,但相信我,事实并非如此!