Java GUI小程序之图片浏览器

以下是一个简单的图片浏览器示例代码,它包含了图片放大缩小、拖拽、上一张/下一张查看等功能。你可以根据它进行扩展,提高用户体验。

java 复制代码
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ImageViewer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JLabel imageLabel;
    private JScrollPane scrollPane;
    private BufferedImage image;
    private Dimension imageSize;
    private JPanel controlPanel;
    private JSlider zoomSlider;
    private JButton previousButton;
    private JButton nextButton;

    private int currentImageIndex = 0;
    private String[] imagePaths = {"image1.jpg", "image2.jpg", "image3.jpg"};

    private int zoomLevel = 100; // Default zoom level

    public ImageViewer() {
        setTitle("Image Viewer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(800, 600));
        setLayout(new BorderLayout());

        // Create image label and scroll pane
        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scrollPane = new JScrollPane(imageLabel);
        add(scrollPane, BorderLayout.CENTER);

        // Create control panel
        controlPanel = new JPanel();
        controlPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        add(controlPanel, BorderLayout.SOUTH);

        // Create zoom slider
        zoomSlider = new JSlider(SwingConstants.HORIZONTAL, 50, 200, zoomLevel);
        zoomSlider.setMajorTickSpacing(50);
        zoomSlider.setMinorTickSpacing(10);
        zoomSlider.setPaintTicks(true);
        zoomSlider.setPaintLabels(true);
        zoomSlider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                zoomLevel = zoomSlider.getValue();
                updateImage();
            }
        });
        controlPanel.add(zoomSlider);

        // Create previous button
        previousButton = new JButton("Previous");
        previousButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (currentImageIndex > 0) {
                    currentImageIndex--;
                    loadImage();
                }
            }
        });
        controlPanel.add(previousButton);

        // Create next button
        nextButton = new JButton("Next");
        nextButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (currentImageIndex < imagePaths.length - 1) {
                    currentImageIndex++;
                    loadImage();
                }
            }
        });
        controlPanel.add(nextButton);

        // Load the first image
        loadImage();

        // Add mouse listeners to enable dragging
        imageLabel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                imageLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
            }

            public void mouseReleased(MouseEvent e) {
                imageLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            }
        });
        imageLabel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                int dx = e.getX() - (imageSize.width - scrollPane.getViewport().getWidth()) / 2;
                int dy = e.getY() - (imageSize.height - scrollPane.getViewport().getHeight()) / 2;

                int newHValue = scrollPane.getHorizontalScrollBar().getValue() - dx;
                int newVValue = scrollPane.getVerticalScrollBar().getValue() - dy;

                if (newHValue < 0)
                    newHValue = 0;
                if (newVValue < 0)
                    newVValue = 0;
                if (newHValue + scrollPane.getViewport().getWidth() > imageSize.width)
                    newHValue = imageSize.width - scrollPane.getViewport().getWidth();
                if (newVValue + scrollPane.getViewport().getHeight() > imageSize.height)
                    newVValue = imageSize.height - scrollPane.getViewport().getHeight();

                scrollPane.getHorizontalScrollBar().setValue(newHValue);
                scrollPane.getVerticalScrollBar().setValue(newVValue);
            }
        });

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void loadImage() {
        try {
            image = ImageIO.read(new File(imagePaths[currentImageIndex]));
            imageSize = new Dimension(image.getWidth(), image.getHeight());
            updateImage();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "Error loading image: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateImage() {
        int newWidth = (int) (imageSize.width * zoomLevel / 100.0);
        int newHeight = (int) (imageSize.height * zoomLevel / 100.0);

        BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        scaledImage.getGraphics().drawImage(image, 0, 0, newWidth, newHeight, null);

        imageLabel.setIcon(new ImageIcon(scaledImage));
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // Ignore
        }
        new ImageViewer();
    }

}

运行效果如下:

相关推荐
捕鲸叉16 分钟前
C++设计模式和编程框架两种设计元素的比较与相互关系
开发语言·c++·设计模式
未知陨落1 小时前
数据结构——二叉搜索树
开发语言·数据结构·c++·二叉搜索树
大波V51 小时前
设计模式-参考的雷丰阳老师直播课
java·开发语言·设计模式
无敌最俊朗@1 小时前
unity3d————接口基础知识点
开发语言·c#
winfredzhang1 小时前
如何使用 python 中的 Pillow 创建可自定义的图标生成器
python·pillow·图标·png
一丝晨光2 小时前
gcc 1.c和g++ 1.c编译阶段有什么区别?如何知道g++编译默认会定义_GNU_SOURCE?
c语言·开发语言·c++·gnu·clang·gcc·g++
qq_273900232 小时前
pytorch detach方法介绍
人工智能·pytorch·python
南城花随雪。2 小时前
Spring框架之装饰者模式 (Decorator Pattern)
java·开发语言·装饰器模式
究极无敌暴龙战神X2 小时前
前端学习之ES6+
开发语言·javascript·ecmascript
虞书欣的62 小时前
Python小游戏24——小恐龙躲避游戏
开发语言·python·游戏·小程序·pygame