ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 如何使这个GUI布局正确?

2019-06-25 00:59:05  阅读:139  来源: 互联网

标签:java swing


我想要这个:

我试过这个:

    // Vertically center
    formatbp.setLayout (new GridBagLayout()); // formatbp is a JPanel
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;

    rbpanel.setLayout(new BoxLayout(rbpanel, BoxLayout.PAGE_AXIS)); // rbpanel is also a JPanel
    rb = new ButtonGroup();
    rbpanel.add(new JLabel("Words are seperated by: "));

    rbLinesOrTabs.setSelected(true);
    rb.add(rbLinesOrTabs);
    rbpanel.add(rbLinesOrTabs);
    rbLinesOrTabs.addActionListener(this);

    rbotherpanel = new JPanel(new FlowLayout());
    rb.add(rbOther);
    rbpanel.add(rbOther);
    rbOther.addActionListener(this);

    othercharfield.setEnabled(false); // Is going to be enabled when rbOther gets selected (and disabled again when rbLinesOrTabs is selected again), that is where the actionlisteners are for
    rbotherpanel.add(othercharfield);

    rbpanel.add(rbotherpanel);

    formatbp.add(rbpanel,gbc);
    formatbp.add(formatb,gbc); // formatb is the button

(大多数在代码中早期初始化的对象)

但这是结果:

我究竟做错了什么?

编辑:我发现我在这里弄错了:

rbpanel.add(rbOther);

应该是:

rbotherpanel.add(rbOther);

现在我得到:

更好,但其他项目没有正确对齐. (你可以看到右侧有点)

解决方法:

使用MigLayout的一体化方法(是的,它真的是我目前最喜欢的:-)

    MigLayout layout = new MigLayout("debug", "[][]");
    JComponent content = new JPanel(layout);
    content.add(new JLabel("Words are separated by: "), "span");
    JRadioButton radio = new JRadioButton("Lines or tabs");
    content.add(radio, "wrap");
    // split the cell so it will contain both the other button
    // and the textfield
    content.add(new JRadioButton("Other:"), "split 2");
    // get the right margin of the upper radiobutton
    int rightMargin = radio.getInsets().right; 
    content.add(new JTextField(), "grow, wrap, " +
        // remove the gap to the preceding radiobutton
            "gapx 0, " +
        // set the padding to compensate the right edge
            "pad 0 0 0 -" + rightMargin + "px");
    content.add(new JButton("Format"), "span, center");
    showInFrame(content, "align to button text");

共享单元格中精细调整的视觉结果有点依赖于LAF.在Windows中看起来不错,在Nimbus中看起来不太好(后者在没有任何补偿的情况下看起来最好),所以你需要进行一些实验.

标签:java,swing
来源: https://codeday.me/bug/20190625/1283629.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有