BorderLayout,无法设置手动位置 - SWING Java

BorderLayout, Impossible to set a manual Location - SWING Java

我有问题,我实现了 BorderLayout JPanel。如果我尝试在北区移动一个示例按钮,它会停留在默认位置。 这是我的代码:

public class Window extends JFrame{


Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time;
double temperature=0.0;

public static void main(String[] args) {
    new Window();

}

public Window()
{
    System.out.println("je suis là");
    this.setSize(700,400);
    this.setLocationRelativeTo(null);
    this.setResizable(true);
    this.setTitle("Assignment2 - CPU temperature");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    container = new JPanel(new BorderLayout());


    north = new JPanel();
    ip = new JButton ("New");
    ip.setPreferredSize(new Dimension(100,50));
    ip.setLocation(0, 0);
    north.add(ip);
    print = new JButton ("Print");
    north.add(print);

    north.add(new JLabel("Time Step (in s): "));
    timeStep = new JTextArea("10",1,5);
    north.add(timeStep);
    start = new JButton("OK");
    ListenForButton lForButton = new ListenForButton();
    start.addActionListener(lForButton);
    north.add(start);


    south = new JPanel();
    legend = new JLabel("Legends are here");
    south.add(legend);

    west = new JPanel();
    JLabel temp = new JLabel("°C");
    west.add(temp);

    container.add(north, BorderLayout.NORTH);
    container.add(west,BorderLayout.WEST);
    container.add(pan, BorderLayout.CENTER);
    container.add(south, BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
}

例如,我希望我的 "New" 按钮位于 window 的左上角,方法是编写 "ip.setLocation(0,0);"

Window

默认情况下它保持在中心..

有什么想法吗?

您尝试做的是使用 AbsoluteLayout instead of a BorderLayout,BorderLayout 使用基本方向设置窗格上的对象,例如北、东、南、西和中心。您可能需要查看 BorderLayout 的 JavaDoc。

例如,您需要将 north 面板设置为 BorderLayout()

north.setLayout(new BorderLayout());

Oracle Documentation about BorderLayout

A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.


解决方案

north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
ip.setPreferredSize(new Dimension(100,50));
print = new JButton ("Print");
north.add(ip, BorderLayout.WEST);

JPanel centerPanel = new JPanel();
centerPanel.add(print);
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("10",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
centerPanel.add(start);

north.add(centerPanel, BorderLayout.CENTER);

北面板现在由以下两部分组成:

ip (JButton) 和 centerPanel(JPanel) 包含其余组件。


输出