繁体   English   中英

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);
}

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

窗口

并且默认情况下它保持在中心。

有任何想法吗 ?

关于BorderLayout的Oracle文档

边框布局会布置一个容器,并对其组件进行排列和调整大小以适合五个区域:北,南,东,西和中心。


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);

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

ipJButton )和centerPanelJPanel )包含其余组件。


产量

在此处输入图片说明

您想要做的是使用AbsoluteLayout而不是BorderLayout ,BorderLayout使用Cardinal方向在窗格上设置对象,例如North,East,South,West和Center。 您可能需要查看JavaDoc for BorderLayout。

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

north.setLayout(new BorderLayout());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM