GridLayout的FlowLayout不显示组件?

mat*_*ean 3 java swing layout-manager

我正在创建一个应用程序,作为某种类型的中心,用户可以将快捷方式存储到他们喜欢的应用程序并轻松启动它们.不过,我遇到了一些问题FlowLayout.当我使用时GridLayout,组件显示完美.当我使用时FlowLayout,根本没有任何显示.

网格布局: 网格布局

FlowLayout中: 的FlowLayout

我所改变的只是LayoutManager.当我打电话时getComponentCount,他们都回答9.

我觉得这个职位是很长,所以我把我的一个片断代码的代码整洁(从引擎收录)

预先感谢您的帮助!

mKo*_*bel 6

1)FlowLayout非常接受PreferredSize来自JComponent,每个人JComponents都可以Dimension在屏幕上有所不同

例子(uncomnent getMinimumSize&getMinimumSize)

import java.awt.*;
import javax.swing.*;

public class CustomComponent extends JFrame {

    private static final long serialVersionUID = 1L;

    public CustomComponent() {
        setTitle("Custom Component Test / BorderLayout");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
    }

    public void display() {
        add(new CustomComponents0(), BorderLayout.NORTH);
        add(new CustomComponents0(), BorderLayout.CENTER);
        add(new CustomComponents0(), BorderLayout.SOUTH);
        add(new CustomComponents0(), BorderLayout.EAST);
        pack();
        // enforces the minimum size of both frame and component
        setMinimumSize(getMinimumSize());
        setPreferredSize(getPreferredSize());
        setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                CustomComponent main = new CustomComponent();
                main.display();
            }
        };
        javax.swing.SwingUtilities.invokeLater(r);
    }
}

class CustomComponents0 extends JLabel {

    private static final long serialVersionUID = 1L;

    /*@Override
    public Dimension getMinimumSize() {
    return new Dimension(200, 100);
    }

    @Override
    public Dimension getPreferredSize() {
    return new Dimension(300, 200);
    }*/
    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}
Run Code Online (Sandbox Code Playgroud)

2)GridLayou为每个创建比例区域JComponents,然后只接受JComponent更大的Dimnesion来自PreferredSize

3)因为GridLayout我在谈论方法pack(),而不是在那里JFrame#setSize(),因为FLowLayout没关系,