將圖像縮圖加入網格佈局
挑戰:
挑戰:
解決方案:
要在SpringLayout 中顯示縮圖網格,您需要實作一個自訂容器。這是改進的回應:
改進的回應:
將ImageGridPanel 執行個體加約來定位ImageGridPanel 並調整其大小。
將 ImagePane 元件加入 ImageGridPanel。
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ImageGrid { public static void main(String[] args) { // Create the frame and panel. JFrame frame = new JFrame("Image Grid"); JPanel panel = new JPanel(); frame.add(panel, BorderLayout.CENTER); // Create the custom image grid panel. ImageGridPanel imageGridPanel = new ImageGridPanel(); panel.add(imageGridPanel, BorderLayout.CENTER); // Add thumbnails to the image grid panel. for (int i = 0; i < 10; i++) { imageGridPanel.addImage(new ImageIcon("image" + i + ".png")); } // Set the frame properties. frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(600, 400); frame.setLocationRelativeTo(null); frame.setVisible(true); } static class ImageGridPanel extends JPanel { private List<ImageIcon> images; public ImageGridPanel() { setBackground(Color.WHITE); setLayout(null); images = new ArrayList<>(); } public void addImage(ImageIcon image) { images.add(image); invalidate(); repaint(); } @Override public Dimension getPreferredSize() { int numImages = images.size(); int numRows = (int) Math.ceil(Math.sqrt(numImages)); int numCols = (int) Math.ceil(numImages / numRows); int width = numCols * 100; int height = numRows * 100; return new Dimension(width, height); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int numImages = images.size(); int numRows = (int) Math.ceil(Math.sqrt(numImages)); int numCols = (int) Math.ceil(numImages / numRows); int width = getWidth() / numCols; int height = getHeight() / numRows; for (int i = 0; i < numImages; i++) { ImageIcon image = images.get(i); int row = i / numCols; int col = i % numCols; g.drawImage(image.getImage(), col * width, row * height, null); } } } }
程式碼片段:
以上是如何將可捲動影像縮圖整合到 SpringLayout 網格中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!