gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:09:14 25 4
gpt4 key购买 nike

我遇到了问题,我实现了 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);
}

例如,我希望通过编写“ip.setLocation(0,0);”将“新建”按钮放置在窗口的左上角

Window

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

有什么想法吗?

最佳答案

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) 包含其余组件。

<小时/>

输出

enter image description here

关于java - BorderLayout,无法设置手动位置 - SWING Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com