繁体   English   中英

Java GUI布局问题

[英]Java GUI Layout Issues

我正在尝试使用Java创建一个简单的程序,该程序需要顶部8个JLabels ,并且在其正下方有一个JButton 我尝试使用BoxLayout然后使用FlowLayout ,但是发生的是JLabels在程序开始时消失了。 单击该button ,所有内容都会正确显示,但是您必须手动调整窗口大小。 有人可以解释我在做什么错吗? 谢谢!

public class ProgramUI {
   private JButton _jbutton; 
   private ArrayList<JLabel> _jlabels;
   private JFrame _jframe; 
   private JPanel _top, _bottom; 

public ProgramUI(){
_jframe = new JFrame (); 
_jframe.getContentPane().setLayout(new BoxLayout(_jframe.getContentPane(), BoxLayout.Y_AXIS));

_top = new JPanel();
_jframe.add(_top);

_bottom = new JPanel();
_jframe.add(_bottom);

_top.setLayout(new FlowLayout(FlowLayout.LEFT));
_bottom.setLayout(new FlowLayout(FlowLayout.LEFT));

_jlabels = new ArrayList<JLabel>();
for (int i=0; i<8; i++) {
    JLabel label = new JLabel();
    _jlabels.add(label); 
    _top.add(label);
    //...rest of code is not relevant
 }

 _jbutton = new JButton();  
    _bottom.add(_jbutton);

_jframe.pack();
_jframe.setVisible(true);
_jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
} 

我不推荐FlowLayoutBoxLayout BoxLayout非常简单且不可移植。 FlowLayout甚至不是一个布局管理器,只是一个玩笑。

我建议使用内置的GroupLayout或第三方MigLayout 您需要花一些时间来学习如何创建良好的布局。

这是您使用MigLayout的示例。

package com.zetcode;

import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import net.miginfocom.swing.MigLayout;

public class ProgramUI extends JFrame {

    public ProgramUI() {

        initUI();
    }

    private void initUI() {

        setLayout(new MigLayout("nogrid"));

        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"));
        add(new JLabel("Label"), "wrap");
        add(new JButton("Button"));

        pack();

        setTitle("MigLayout example");
        setLocationRelativeTo(null);        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            ProgramUI ex = new ProgramUI();
            ex.setVisible(true);
        });
    }
}

屏幕截图:

范例截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM