more efficient layout than Box

和自甴很熟 提交于 2019-11-29 15:12:34

Why don't you just use a JList and implement a cell renderer?

Or more flexibility with a JTable and implement a table cell renderer (returns a Component instead)?

trashgod

Based on this example, the following code loafs doing 16 labels at 10 Hz.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

/** @see https://stackoverflow.com/questions/6605554 */
public class ImageLabelPanel extends Box implements ActionListener {

    private static final int N = 16;
    private final List<JLabel> list = new ArrayList<JLabel>();
    private final Timer timer = new Timer(100, this);

    ImageLabelPanel() {
        super(BoxLayout.Y_AXIS);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(new File("image.jpg"));
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        for (int r = 0; r < N; r++) {
            int w = bi.getWidth();
            int h = bi.getHeight() / N;
            BufferedImage b = bi.getSubimage(0, r * h, w, h);
            list.add(new JLabel(new ImageIcon(b)));
        }
        createPane();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setVisible(true);
        timer.start();
    }

    private void createPane() {
        this.removeAll();
        for (JLabel label : list) {
            add(label);
        }
        this.revalidate();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Collections.shuffle(list);
        createPane();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

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