【问题标题】:Placing JTextFields in a JFrame of a Java GUI在 Java GUI 的 JFrame 中放置 JTextField
【发布时间】:2012-01-16 06:28:21
【问题描述】:

我有:

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);}
    }

我的问题是我不希望两个 TextField 出现在 Activate 和 Deactivate 按钮的右侧但在它们下方。我该如何解决?

【问题讨论】:

    标签: java swing jframe jtextfield layout-manager


    【解决方案1】:

    我可以建议您对父组件使用 Null 布局吗?

    setLayout(null);

    然后使用 setBounds(xPos,yPos, Width, Height);

    在面板上定位组件等?

    这样做会阻止 Java 的 UI 管理器管理 Frame、Panel 等组件。

    这似乎是最简单且不那么痛苦的方法。

    问候

    【讨论】:

    • -1 表示空布局建议。布局管理的存在是有原因的。
    • 好的,认为这是最简单的,那么您可以尝试 GridBagLayout,它还需要您设置行和列来定位组件。 GridBagLayout。它可能有效,但有很多麻烦。
    【解决方案2】:

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

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

    这将使用Grid Layout Manager 建立一个具有 2 列和 2 行的网格,然后您的组件将被放入其中。

    您当前使用的布局管理器FlowLayout 仅将内容添加到当前行的末尾。但是,一旦到达窗格的受限边缘,它就会环绕。 您还应该检查其他布局管理器here

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

    content.add(networkIdField, gridConstraints);
    

    在链接的教程中查看更多信息。

    【讨论】:

    • +1 GridLayout 也可以很好地嵌套,如图所示here。
    猜你喜欢
    • 1970-01-01
    • 2015-12-18
    • 2012-08-23
    • 2023-03-30
    • 2013-02-23
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多