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

时间:2011-11-04 06:09:03

标签: java swing jframe layout-manager

我有标签和JButtons我想在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中管理对象的位置?

5 个答案:

答案 0 :(得分:4)

使用正确的LayoutManager。例如。的GridBagLayout。

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

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

答案 1 :(得分:3)

FlowLayout为您提供了一些选择。看here

例如

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

答案 2 :(得分:2)

答案 3 :(得分:0)

Netbeans GUI Builder非常棒。我建议你调查一下。

http://netbeans.org/kb/docs/java/quickstart-gui.html

答案 4 :(得分:0)

使用Netbeans GUI Builder。它确实有缺点。比如你无法删除自动创建的ActionListeners。