Swing dynamic(auto) fit-layouting

好久不见. 提交于 2019-12-23 05:48:22

问题


Considering 100(dynamic) JLabel Object, and I want to show them inside a resizable JPanel.
Currently I use grid bag layout (2 columns and 50 rows), but when user resizes and expands the form, I want to have(for example) 4 columns and 25 rows, and same for small form(1 column, and 100 rows), in other way fill up the whole panel(no any white spaces).
I know this is should be done manually, currently I redraw(repaint) all members once user resize the form, but I just was wondering if there is any prepared solution to do so.
Thanks in advanced.


回答1:


Have a look at Rob Camick's WrapLayout.

Example use

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

public class TestWrapLayout {
    public TestWrapLayout () {
        ImageIcon icon = new ImageIcon(getClass().getResource("/resources/stackoverflow2.png"));
        JPanel panel = new JPanel(new WrapLayout());
        for (int i = 1; i <= 250; i++) {
            JLabel iconlabel = new JLabel(icon);
            iconlabel.setLayout(new BorderLayout());
            JLabel textlabel = new JLabel(String.valueOf(i));
            textlabel.setHorizontalAlignment(JLabel.CENTER);
            textlabel.setForeground(Color.WHITE);
            textlabel.setFont(new Font("impact", Font.PLAIN,20));
            iconlabel.add(textlabel);
            panel.add(iconlabel);
        }
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(panel));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new TestWrapLayout();
            }
        });
    }
}



回答2:


You can define a custom LayoutManager to position children as you wish in the public void layoutContainer(Container target) method.

Similar example is implemented here http://java-sl.com/tip_columns_flow_layout.html



来源:https://stackoverflow.com/questions/22378509/swing-dynamicauto-fit-layouting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!