Java 摆动布局:垂直流动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4495094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 18:02:11  来源:igfitidea点击:

swing layout: vertical flow

javaswing

提问by pstanton

What LayoutManager should I use to achieve a transposed version of FlowLayout?

我应该使用什么 LayoutManager 来实现 FlowLayout 的转置版本?

Essentially, I want a vertical list which occupies multiple columns if it can't fit all of it's components within one column.

本质上,我想要一个占据多列的垂直列表,如果它不能在一列中容纳它的所有组件。

+------------------------+
| item 1                 |
| item 2                 |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
| item 7                 |
| item 8                 |
+------------------------+

or

或者

+------------------------+
| item 1  item 7         |
| item 2  item 8         |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
+------------------------+

this wrapping logic needs to happen dynamically, ie as the container is resized.

这种包装逻辑需要动态发生,即随着容器的大小调整。

采纳答案by Jason S

I'm working on a solution to my own question(very similar: I need to flow vertically but constrain width horizontally), I got a quick example sort of working and maybe it gets you started with a custom layout manager:

我正在研究我自己的问题的解决方案(非常相似:我需要垂直流动但水平限制宽度),我有一个快速的工作示例,也许它可以让您开始使用自定义布局管理器:

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;
import java.util.Random;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.google.common.collect.Sets;


public class VerticalFlowLayout implements LayoutManager2
{
    final private Set<Component> components = Sets.newLinkedHashSet();
    private int hgap = 0;
    private int vgap = 0;

    public void setHGap(int hgap) { this.hgap = hgap; }
    public void setVGap(int vgap) { this.vgap = vgap; }

    @Override public void addLayoutComponent(Component comp, Object constraints) {
        this.components.add(comp);
    }

    /* these 3 methods need to be overridden properly */
    @Override public float getLayoutAlignmentX(Container target) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override public float getLayoutAlignmentY(Container target) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override public void invalidateLayout(Container target) {
        // TODO Auto-generated method stub

    }


    @Override public void addLayoutComponent(String name, Component comp) {
        this.components.add(comp);
    }

    @Override public void layoutContainer(Container parent) {
        int x = 0;
        int y = 0;
        int columnWidth = 0;
        for (Component c : this.components)
        {
            if (c.isVisible())
            {
                Dimension d = c.getPreferredSize();
                columnWidth = Math.max(columnWidth, d.width);
                if (y+d.height > parent.getHeight())
                {
                    x += columnWidth + this.hgap;
                    y = 0;
                }
                c.setBounds(x, y, d.width, d.height);
                y += d.height + this.vgap;              
            }
        }       
    }

    /* these 3 methods need to be overridden properly */
    @Override public Dimension minimumLayoutSize(Container parent) {
        return new Dimension(0,0);
    }

    @Override public Dimension preferredLayoutSize(Container parent) {
        return new Dimension(200,200);
    }

    @Override public Dimension maximumLayoutSize(Container target) {
        return new Dimension(600,600);
    }


    @Override public void removeLayoutComponent(Component comp) {
        this.components.remove(comp);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("VerticalFlowLayoutTest");    
        VerticalFlowLayout vfl = new VerticalFlowLayout();
        JPanel panel = new JPanel(vfl);
        vfl.setHGap(20);
        vfl.setVGap(2);
        int n = 19;
        Random r = new Random(12345);
        for (int i = 0; i < n; ++i)
        {
            JLabel label = new JLabel(labelName(i,r));
            panel.add(label);
        }

        frame.setContentPane(panel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private static String labelName(int i, Random r) {
        StringBuilder sb = new StringBuilder();
        sb.append("label #");
        sb.append(i);
        sb.append(" ");
        int n = r.nextInt(26);
        for (int j = 0; j < n; ++j)
            sb.append("_");
        return sb.toString();
    }
}

回答by camickr

I modified the GridLayout to layout components by column first instead of by row:

我修改了 GridLayout 以首先按列而不是按行布局组件:

http://forums.oracle.com/forums/thread.jspa?messageID=5716765#5716765

http://forums.oracle.com/forums/thread.jspa?messageID=5716765#5716765

回答by camickr

Either you'll need a custom layout manager or you can use something like a GridBagLayout and control yourself.

您要么需要自定义布局管理器,要么可以使用 GridBagLayout 之类的东西并自行控制。

An example:

一个例子:

Component parent = ...;  
GridBagConstraints c = ...;   
//set other parameters  
c.gridx = 0;  
c.gridy = 0;  
parent.add([component1], c);  
c.gridy++;  
parent.add([component2], c);  
c.gridy++;

回答by user1232972

very easy,you just need this.

很简单,你只需要这个。

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

after this,you just add view to yourPanel and you will get vertical flow layout.

在此之后,您只需将视图添加到您的面板,您将获得垂直流布局。

回答by Soley

This post is quite old :)

这篇文章很老了:)

Codes in below link does not work fine, (calculate the height of invisible items which it is wrong!) http://www.java2s.com/Code/Java/Swing-JFC/AverticallayoutmanagersimilartojavaawtFlowLayout.htm

以下链接中的代码无法正常工作,(计算不可见项目的高度是错误的!) http://www.java2s.com/Code/Java/Swing-JFC/AverticallayoutmanagerssimilartojavaawtFlowLayout.htm

I changed some parts so it works fine now.

我更改了一些部分,所以现在可以正常工作了。

I also clean up insets so, if you need it, please add it yourself. thanks

我也清理了插图,所以如果你需要它,请自己添加。谢谢

package Common;

/**
 * @author Pasban
 */
import java.awt.*;
import java.util.*;

public class VerticalLayout implements LayoutManager {

    public final static int CENTER = 0;
    public final static int RIGHT = 1;
    public final static int LEFT = 2;
    public final static int BOTH = 3;
    public final static int TOP = 1;
    public final static int BOTTOM = 2;
    private int vgap;
    private int alignment;
    private int anchor;
    private Hashtable comps;

    public VerticalLayout() {
        this(5, CENTER, TOP);
    }

    public VerticalLayout(int vgap) {
        this(vgap, CENTER, TOP);
    }

    public VerticalLayout(int vgap, int alignment) {
        this(vgap, alignment, TOP);
    }

    public VerticalLayout(int vgap, int alignment, int anchor) {
        this.vgap = vgap;
        this.alignment = alignment;
        this.anchor = anchor;
    }

    private Dimension layoutSize(Container parent, boolean minimum) {
        Dimension dim = new Dimension(0, 0);
        Dimension d;
        synchronized (parent.getTreeLock()) {
            int n = parent.getComponentCount();
            for (int i = 0; i < n; i++) {
                Component c = parent.getComponent(i);
                if (c.isVisible()) {
                    d = minimum ? c.getMinimumSize() : c.getPreferredSize();
                    dim.width = Math.max(dim.width, d.width);
                    dim.height += d.height;
                    if (i > 0) {
                        dim.height += vgap;
                    }
                }
            }
        }
        Insets insets = parent.getInsets();
        dim.width += insets.left + insets.right;
        dim.height += insets.top + insets.bottom + vgap + vgap;
        return dim;
    }

    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();
        synchronized (parent.getTreeLock()) {
            int n = parent.getComponentCount();
            Dimension pd = parent.getSize();
            int y = 0;
            for (int i = 0; i < n; i++) {
                Component c = parent.getComponent(i);
                Dimension d = c.getPreferredSize();
                if (c.isVisible()) {
                    y += d.height + vgap;
                }
            }
            y -= vgap;
            if (anchor == TOP) {
                y = insets.top;
            } else if (anchor == CENTER) {
                y = (pd.height - y) / 2;
            } else {
                y = pd.height - y - insets.bottom;
            }
            for (int i = 0; i < n; i++) {
                Component c = parent.getComponent(i);
                Dimension d = c.getPreferredSize();
                if (!c.isVisible()) {
                    continue;
                }
                int x = 1;
                int wid = pd.width - 3;
                c.setBounds(x, y, wid, d.height);
                y += d.height + vgap;
            }
        }
    }

    public Dimension minimumLayoutSize(Container parent) {
        return layoutSize(parent, false);
    }

    public Dimension preferredLayoutSize(Container parent) {
        return layoutSize(parent, false);
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public String toString() {
        return getClass().getName() + "[vgap=" + vgap + " align=" + alignment + " anchor=" + anchor + "]";
    }
}

回答by Elloco

The solution of Jason S works for me. The only issue I corrected is I don't have com.google.common.collect.Sets or java.collections.LinkedHashSet libs (Java 7)...

Jason S 的解决方案对我有用。我纠正的唯一问题是我没有 com.google.common.collect.Sets 或 java.collections.LinkedHashSet 库(Java 7)...

so I just replace

所以我只是替换

final private Set<Component> components = Sets.newLinkedHashSet();

by

经过

final private List<Component> components = new LinkedList<>();

and all seems to be ok :)

一切似乎都没问题:)