How to set position of objects in JFrame?

2019-05-18 07:11发布

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() doesnot seem to work here. How to manage the object's position in JFrame?

5条回答
爷、活的狠高调
3楼-- · 2019-05-18 07:53

FlowLayout gives you some options. Look here .

For Example

   FlowLayout layout = new FlowLayout();
   layout.setAlignment(FlowLayout.CENTER);
   c.setLayout(layout);
   c.add(panel);
查看更多
等我变得足够好
4楼-- · 2019-05-18 08:06

The Netbeans GUI Builder is great. I suggest you look into it.

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

查看更多
Evening l夕情丶
5楼-- · 2019-05-18 08:06

Use the Netbeans GUI Builder. It does have downsides though. Such as you can't delete ActionListeners created automatically.

查看更多
唯我独甜
6楼-- · 2019-05-18 08:10

Use proper LayoutManager. E.g. GridBagLayout.

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

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

查看更多
登录 后发表回答