検索
ホームページJava&#&チュートリアル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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Javaプラットフォームの独立性:異なるOSとの互換性Javaプラットフォームの独立性:異なるOSとの互換性May 13, 2025 am 12:11 AM

javaachievesplatformentenceTheTheTheJavavirtualMachine(JVM)、CodetorunondifferentoperatingSystemswithOutModification.thejvmcompilesjavacodeplatform-IndopentedbyTecodeを承認することを許可します

Javaをまだ強力にしている機能Javaをまだ強力にしている機能May 13, 2025 am 12:05 AM

javaispowerfulfulduetoitsplatformindepentence、object-orientednature、richstandardlibrary、performancecapability、andstrongsecurityfeatures.1)platformendependenceallowseplicationStorunonaydevicesupportingjava.2)オブジェクト指向のプログラマン型

トップJava機能:開発者向けの包括的なガイドトップJava機能:開発者向けの包括的なガイドMay 13, 2025 am 12:04 AM

上位のJava関数には、次のものが含まれます。1)オブジェクト指向プログラミング、サポートポリ型、コードの柔軟性と保守性の向上。 2)例外処理メカニズム、トライキャッチ式ブロックによるコードの堅牢性の向上。 3)ゴミ収集、メモリ管理の簡素化。 4)ジェネリック、タイプの安全性の向上。 5)コードをより簡潔で表現力豊かにするためのAMBDAの表現と機能的なプログラミング。 6)最適化されたデータ構造とアルゴリズムを提供するリッチ標準ライブラリ。

Javaは本当にプラットフォームが独立していますか?どのように「一度書く、どこでも実行」が機能する方法Javaは本当にプラットフォームが独立していますか?どのように「一度書く、どこでも実行」が機能する方法May 13, 2025 am 12:03 AM

javaisnotentirelylylyplatformedent dueTojvmvariations andNativeCodeIntegration、ButlargelyHoldSitsworapromise.1)JavacompilestobyteCoderunbythejvm、Cross-Platformexecution.2を許可します

JVMの分解:Javaの実行を理解するための鍵JVMの分解:Javaの実行を理解するための鍵May 13, 2025 am 12:02 AM

thejavavirtualmachine(jvm)isanabstractcomputingmachineculucialforjavaexecutionsiTrunsjavabytecode、「writeonce、runaynay "capability

Javaはまだ新機能に基づいた良い言語ですか?Javaはまだ新機能に基づいた良い言語ですか?May 12, 2025 am 12:12 AM

JavaremainsagoodlanguagedueToitscontinuousevolution androbustecosystem.1)lambdaexpressionsenhancecodereadability andenableFunctionalprogramming.2)streamsalowsolowsolfisitydataprocessing、特に特にlagedatasets.3)硬化系系統系系統系系統系系統

何がJavaを素晴らしいものにしますか?主な機能と利点何がJavaを素晴らしいものにしますか?主な機能と利点May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence、robustoopsupport、extensiveLibraries、andstrongCommunity.1)PlatformentepenteviajvMallowsCodeTorunonVariousPlatforms.2)oopeatureSlikeEncapsulation、遺伝、およびポリモ系系統型皮下皮質皮下Rich

トップ5のJava機能:例と説明トップ5のJava機能:例と説明May 12, 2025 am 12:09 AM

Javaの5つの主要な特徴は、多型、Lambda Expressions、StreamSapi、ジェネリック、例外処理です。 1。多型により、さまざまなクラスのオブジェクトを一般的なベースクラスのオブジェクトとして使用できます。 2。Lambda式は、コードをより簡潔にし、特にコレクションやストリームの処理に適しています。 3.ストリームサピは、大規模なデータセットを効率的に処理し、宣言操作をサポートします。 4.ジェネリックは、タイプの安全性と再利用性を提供し、型刻印中にタイプエラーがキャッチされます。 5.例外処理は、エラーをエレガントに処理し、信頼できるソフトウェアを作成するのに役立ちます。

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 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。