如何在JFrame中设置对象的位置? [英] How to set position of objects in JFrame?

查看:259
本文介绍了如何在JFrame中设置对象的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有标签和JButton我想在JFrame中定义位置。

I have Labels and JButtons i want to define the position in 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中管理对象的位置?

setLocation() doesnot seem to work here. How to manage the object's position in JFrame?

推荐答案

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

Use proper LayoutManager. E.g. GridBagLayout.

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

Or you can combine multiple nested panels assigning own LayoutManager for each panel.

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

The worst way is to set layout to null and use setBounds()

这篇关于如何在JFrame中设置对象的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆