首页 > 解决方案 > FlowLayout不会换行

问题描述

我正在尝试使用 FlowLayout 在另一个 JPanel 中添加可变数量的 JPanel(每个包含 2 个标签)。当添加了太多面板而不是转到新行时,它们会消失在边框之外

我尝试了许多类型的布局、设置大小、最大尺寸,但没有任何变化。

public class AlbumView extends javax.swing.JFrame
{
    private Album A;

    public AlbumView()
    {
        initComponents();
        A = new Album();

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;
        this.setLocation(x, y);

        pnlCategorie.setLayout(new FlowLayout(FlowLayout.TRAILING, 10, 10));

        /*
        Insert of many elements in the Album
        */

        aggiornaAlbum();
    }

    public void aggiornaAlbum()
    {
        for(int i = 0; i < A.getDim(); i++)
        {
            Categoria c = A.getCategoria(i);

            JPanel pnl = new JPanel();
            pnl.setName(c.getNome());
            JLabel lb1, lb2;
            ImageIcon img = new ImageIcon(c.getPhoto(0).getImg(95, 95));  //da cambiare lo 0 con un numero casuale tra le foto disponibili
            lb1 = new JLabel(img, JLabel.CENTER);
            lb2 = new JLabel(c.getNome(), JLabel.CENTER);


            pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));

            pnl.setBorder(BorderFactory.createLineBorder(Color.black));
            pnl.add(lb1);
            pnl.add(lb2);
            //pnl.revalidate();
            //pnl.repaint();

            pnlCategorie.add(pnl);
        }

        //ADDED AFTER COMMENT, NOTHING CHANGED (but probably it's because i didn't get exaclty what to do
        pnlCategorie.revalidate();
        pnlCategorie.repaint();
    }

pnlCategorie 是使用 NetBeans swing 创建的。

我希望在适合较大 jPanel 的 jpanel 数量之后,下一个进入新行

出现的示例(我正在使用一些示例图像,不要判断): 例子

标签: javaswinglayout-managerflowlayout

解决方案


推荐阅读