简体   繁体   中英

Java GUI Layout Issues

I'm trying to make a simple program in Java that requires 8 JLabels on the top with one JButton directly below it. I tried using BoxLayout and then FlowLayout , but what happens is the JLabels disappear at the start of the program. When the button is clicked, everything is displayed properly, but you have to manually resize the window. Could someone explain what I'm doing wrong? Thanks!

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

I don't recommend neither FlowLayout nor BoxLayout . BoxLayout is very simplistic and non-portable. FlowLayout is not even a layout manager, it's a joke.

I recommend to use either built-in GroupLayout or third-party MigLayout . You need to dedicate some time for learning how to create a good layout.

Here is your example with 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);
        });
    }
}

Screenshot:

范例截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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