如何在JFrame中设置对象的位置?

3

我有标签和按钮,我想在JFrame中定义它们的位置。

import java.awt.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.*;

public class GuiFrame extends JFrame {

    public static void main(String[] args) throws UnknownHostException {

        JFrame f = new JFrame("This is a test");
        f.setSize(400, 150);
        JRadioButton ButtonServer = new JRadioButton("Server");
        JRadioButton ButtonClient = new JRadioButton("Client");

        InetAddress thisIp = InetAddress.getLocalHost();

        Label lip = new Label("Your IP is : " + thisIp.getHostAddress());
        Label setup = new Label("Setup as ");
        JButton ButtonOk = new JButton("OK");

        Container content = f.getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        content.add(lip);
        content.add(setup);
        content.add(ButtonServer);
        content.add(ButtonClient);
        content.add(ButtonOk);
        // f.addWindowListener(new ExitListener());
        f.setVisible(true);
    }
}

在这里,setLocation()似乎不起作用。如何管理JFrame中对象的位置?


4
请查看课程:在容器内布局组件 - trashgod
4个回答

4

使用适当的 LayoutManager。例如,使用 GridBagLayout

或者您可以组合多个嵌套面板,并为每个面板分配自己的 LayoutManager

最糟糕的方法是将布局设置为 null 并使用 setBounds()


同意,setLayout null 不是一个好的做法! - Handsken
我见过一些LayoutManager,但是似乎没有一个LayoutManager具有在JFrame中设置位置(x,y)的功能。有这样的吗? - nebula

3

FlowLayout提供了一些选项。请在这里查看。

例如

   FlowLayout layout = new FlowLayout();
   layout.setAlignment(FlowLayout.CENTER);
   c.setLayout(layout);
   c.add(panel);


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接