찾다
Javajava지도 시간Java Swing의 그리드 레이아웃에 이미지 축소판을 어떻게 추가할 수 있습니까?

How Can I Add Image Thumbnails to a Grid Layout in Java Swing?

이미지를 그리드 레이아웃에 썸네일로 추가할 수 있나요?

이 쿼리는 그리드 레이아웃 내의 작은 이미지 썸네일 그리드 생성과 관련이 있습니다. 프레임의 SpringLayout. 잠재적으로 수많은 이미지를 수용하려면 스크롤 창이 필요합니다. 그러나 가장 큰 과제는 SpringLayout을 사용하여 이러한 그리드와 같은 배열을 구현하는 방법을 이해하는 것입니다.

솔루션

SpringLayout 내에서 썸네일 배치를 처리하려고 시도하는 대신 다음을 사용하는 것이 좋습니다. 이미지의 기초로 사용되는 스크롤 창 내의 컨테이너입니다. 이렇게 하면 격자형 구조에 이미지를 추가할 수 있습니다.

다음 예에서는 이를 달성하는 방법을 보여줍니다.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ImageGrid {

    public static void main(String[] args) {
        new ImageGrid();
    }

    public ImageGrid() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setResizable(true);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel imagesPane;

        public TestPane() {
            setLayout(new BorderLayout());
            imagesPane = new JPanel(new WrapLayout());
            add(new JScrollPane(imagesPane));
            JButton scan = new JButton("Scan");
            scan.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String path = "C:\Users\shane\Dropbox\Ponies";
                    File[] files = new File(path).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            String name = pathname.getName().toLowerCase();
                            return pathname.isFile() && (name.endsWith(".png")
                                    || name.endsWith(".jpg")
                                    || name.endsWith(".gif"));
                        }
                    });
                    imagesPane.removeAll();
                    for (File file : files) {
                        try {
                            ImagePane pane = new ImagePane(file);
                            imagesPane.add(pane);
                        } catch (Exception exp) {
                            exp.printStackTrace();
                        }
                    }
                    imagesPane.revalidate();
                    imagesPane.repaint();
                }
            });
            add(scan, BorderLayout.SOUTH);
        }
    }

    public class ImagePane extends JPanel {

        private Image img;

        public ImagePane(File source) throws IOException {
            img = ImageIO.read(source);
            if (img.getWidth(this) > 200 || img.getHeight(this) > 200) {
                int width = img.getWidth(this);
                int height = img.getWidth(this);
                float scaleWidth = 200f / width;
                float scaleHeight = 200f / height;
                if (scaleWidth > scaleHeight) {
                    width = -1;
                    height = (int)(height * scaleHeight);
                } else {
                    width = (int)(width * scaleWidth);
                    height = -1;
                }
                img = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (img != null) {
//                int width = img.getWidth();
//                int height = img.getHeight();
//                float scale = 1f;
//                AffineTransform at = new AffineTransform();
//                at.translate(
//                        (getWidth() / 2) - ((img.getWidth() * scale) / 2),
//                        (getHeight() / 2) - ((img.getHeight() * scale) / 2));
//                at.scale(scale, scale);
//                g2d.setTransform(at);
                g2d.drawImage(img, 0, 0, this);
            }
            g2d.dispose();
        }
    }

    /**
     * FlowLayout subclass that fully supports wrapping of components.
     */
    public class WrapLayout extends FlowLayout {

        private Dimension preferredLayoutSize;

        /**
         * Constructs a new
         * <code>WrapLayout</code> with a left alignment and a default 5-unit
         * horizontal and vertical gap.
         */
        public WrapLayout() {
            super();
        }

        /**
         * Constructs a new
         * <code>FlowLayout</code> with the specified alignment and a default 5-unit
         * horizontal and vertical gap. The value of the alignment argument must be
         * one of
         * <code>WrapLayout</code>,
         * <code>WrapLayout</code>, or
         * <code>WrapLayout</code>.
         *
         * @param align the alignment value
         */
        public WrapLayout(int align) {
            super(align);
        }

        /**
         * Creates a new flow layout manager with the indicated alignment and the
         * indicated horizontal and vertical gaps.
         * <p>
         * The value of the alignment argument must be one of
         * <code>WrapLayout</code>,
         * <code>WrapLayout</code>, or
         * <code>WrapLayout</code>.
         *
         * @param align the alignment value
         * @param hgap the horizontal gap between components
         * @param vgap the vertical gap between components
         */
        public WrapLayout(int align, int hgap, int vgap) {
            super(align, hgap, vgap);
        }

        /**
         * Returns the preferred dimensions for this layout given the
         * <i>visible</i> components in the specified target container.
         *
         * @param target the component which needs to be laid out
         * @return the preferred dimensions to lay out the subcomponents of the
         * specified container
         */
        @Override
        public Dimension preferredLayoutSize(Container target) {
            return layoutSize(target, true);
        }

        /**
         * Returns the minimum dimensions needed to layout the <i>visible</i>
         * components contained in the specified target container.
         *
         * @param target the component which needs to be laid out
         * @return the minimum dimensions to lay out the subcomponents of the
         * specified container
         */
        @Override
        public Dimension minimumLayoutSize(Container target) {
            Dimension minimum = layoutSize(target, false);
            minimum.width -= (getHgap() + 1);
            return minimum;
        }

        /**
         * Returns the minimum or preferred dimension needed to layout the target
         * container.
         *
         * @param target target to get layout size for
         * @param preferred should preferred size be calculated
         * @return the dimension to layout the target container
         */
        private Dimension layoutSize(Container target, boolean preferred) {
            synchronized (target.getTreeLock()) {
                //  Each row must fit with the width allocated to the containter.</p>

위 내용은 Java Swing의 그리드 레이아웃에 이미지 축소판을 어떻게 추가할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Java는 여전히 새로운 기능을 기반으로 좋은 언어입니까?Java는 여전히 새로운 기능을 기반으로 좋은 언어입니까?May 12, 2025 am 12:12 AM

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

Java가 위대하게 만드는 이유는 무엇입니까? 주요 기능과 이점Java가 위대하게 만드는 이유는 무엇입니까? 주요 기능과 이점May 12, 2025 am 12:11 AM

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

상위 5 개의 Java 기능 : 예와 설명상위 5 개의 Java 기능 : 예와 설명May 12, 2025 am 12:09 AM

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.

Java의 최고 기능은 성능과 확장 성에 어떤 영향을 미칩니 까?Java의 최고 기능은 성능과 확장 성에 어떤 영향을 미칩니 까?May 12, 2025 am 12:08 AM

java'stopfeaturessificeNificeLynitySteperformanceandscalibers

JVM Internals : Java Virtual Machine에 깊숙이 다이빙JVM Internals : Java Virtual Machine에 깊숙이 다이빙May 12, 2025 am 12:07 AM

JVM의 핵심 구성 요소에는 클래스 로더, runtimedataarea 및 executionEngine이 포함됩니다. 1) 클래스 로더는 클래스 및 인터페이스로드, 연결 및 초기화를 담당합니다. 2) runtimedataarea에는 Methodarea, 힙, 스택, Pcregister 및 NativeMethodStacks가 포함되어 있습니다. 3) ExecutionEngine은 바이트 코드의 실행 및 최적화를 담당하는 통역사, JitCompiler 및 GarbageCollector로 구성됩니다.

자바를 안전하고 안전하게 만드는 기능은 무엇입니까?자바를 안전하고 안전하게 만드는 기능은 무엇입니까?May 11, 2025 am 12:07 AM

Java'sSafetyandsecurityArebolsteredBy : 1) 강력한, reventStype relatedErrors; 2) AutomaticMemoryManagementViageGageCollection; 3) 샌드 박스, 고립 코드 프롬 시스템; 및 4) 강도 핸드 링, 보장

필수 Java 기능 : 코딩 기술 향상필수 Java 기능 : 코딩 기술 향상May 11, 2025 am 12:07 AM

javaoffersseveralkeyfeaturestenhancecodingskills : 1) 객체 지향적 인 프로그래밍 allowsmodelingreal-worldentities, 예시적인 혈관 림 모르 즘 .2) 예외적 인 handlingprovidesrobusterrormanagement.3) LambdaexorsionssimplifyOperations, 개선

JVM 가장 완전한 가이드JVM 가장 완전한 가이드May 11, 2025 am 12:06 AM

thejvmisacrucialcomponentsThrunsjavacodebacodebybacodebytranslatingitintintintincinomachine-specificinstructions, 영향력 성능, 보안 및 포트 가능성

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구