有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing在Java GUI的JFrame中放置JTextFields

我有:

public class BaseStationFrame1 extends JFrame
{

    JButton activateButton;
    JButton deactivateButton;
    BaseStation bs;

    JTextField networkIdField;
    JTextField portField;



    public BaseStationFrame1(BaseStation _bs){

        bs = _bs;

        setTitle("Base Station");
        setSize(600,500); 
        setLocation(100,200);  
        setVisible(true);

        activateButton = new JButton("Activate");
        deactivateButton = new JButton("Deactivate");
        Container content = this.getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout()); 
        content.add(activateButton);
        content.add(deactivateButton);

        networkIdField = new JTextField("networkId : "+ bs.getNetworkId());
        networkIdField.setEditable(false);

        content.add(networkIdField);

        portField = new JTextField("portId : "+ bs.getPort());
        portField.setEditable(false);

        content.add(portField);}
    }

我的问题是,我不希望这两个文本字段出现在ActivateDeactivate按钮的右侧,而是在它们下面。我该怎么解决


共 (1) 个答案

  1. # 1 楼答案

    指定布局管理器,如下所示:

    content.setLayout(new GridLayout(2,2));
    

    这将使用Grid Layout Manager 建立一个包含两列和两行的网格,然后将组件放置在其中

    当前使用的布局管理器FlowLayout只会将内容添加到当前行的末尾。不过,当它到达窗格的受约束边缘时,它会卷起。 您还应该检查其他布局管理器here

    也可以使用GridBagLayout,但必须指定一个GridBagConstraints对象,然后将其添加到各个元素旁边,如下所示:

    content.add(networkIdField, gridConstraints);
    

    请参见链接教程中的更多内容