Pregunta

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.

¿Fue útil?

Solución

Have a look at Rob Camick's WrapLayout.

Example use

enter image description hereenter image description here

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

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top