统计
  • 建站日期:2019-12-01
  • 文章总数:2033 篇
  • 评论总数:2128 条
  • 分类总数:21 个
  • 最后更新:12月3日
文章 未分类

用Java Swing制作简易电子相册

程序员阿鑫
首页 未分类 正文

一、前言:

声明:本篇文章转载至CSDN博客,如有侵权请联系博主删除

程序首界面,我感觉程序中部分代码可以用作其他程序使用,例如网盘界面,上传文件啥的...再次感谢CSDN LyRics1996


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第1
张图片

目前代码实现了文件夹读取,缩略图展示这两个功能,剩余功能大家看界面也能猜到了,有生之年系列吧,下次想写再说吧。

二、导包

Jar包导入:


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第2
张图片

下载链接:https://search.maven.org/artifact/net.coobird/thumbnailator/0.4.8/jar

三、程序结构

方便查找、运行,不按这个结构也行


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第3
张图片

其中日志模块还没有写。

四、代码

1.Main

package imageView.cxyax.main;

import java.awt.EventQueue;

import imageView.lyrics.ui.ImageViewFrameUI;

public class Main {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new ImageViewFrameUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

2、service

package imageView.cxyax.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;

import imageView.lyrics.ui.AlbumTreeUI;
import imageView.lyrics.ui.ImageUI;
import imageView.lyrics.util.ResizeImage;

public class AlbumService {
    enum ImageType{
        jpg,jpeg,png,CR2
    }
    private AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance(); 
    private ImageUI imageUI = ImageUI.getInstance();

    private String browseFolder() {
        // 拿到文件系统
        FileSystemView fsv = FileSystemView.getFileSystemView();
        // 设置过滤器
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Image File","jpg","jpeg","png");
        // 修改为英文 
        JFileChooser.setDefaultLocale(Locale.US);
        // 实例化
        JFileChooser fileChooser = new JFileChooser();
        // 设置当前工作目录为桌面
        fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
        // 设置标头
        fileChooser.setDialogTitle("select");
        // 设置文件选择类型
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        // 移除所有文件过滤模式
        fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
        // 添加文件过滤
        fileChooser.setFileFilter(fileNameExtensionFilter);
        // 拿到操作结果
        int result = fileChooser.showOpenDialog(null);
        // 判断操作结果
        if(result == JFileChooser.APPROVE_OPTION) {
            // 打印所选文件路径
            return fileChooser.getSelectedFile().toString();
        }
        return null;
    }
    private void ergodicImage(String path,ArrayList<String> list) {
        DefaultMutableTreeNode parent = albumTreeUI.addAlbum(path);
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            String temp = tempList[i].toString();
            if (tempList[i].isFile() && isImage(temp)) {
                albumTreeUI.addImage(parent, temp);
                String outPath = "thumbnail"+temp.substring(temp.lastIndexOf("")+1, temp.lastIndexOf("."))+"Temp.jpg";
                ResizeImage.generateFixedSizeImage(temp, outPath);
                imageUI.addImage(outPath);
            }
            if (tempList[i].isDirectory()) {
                ergodicImage(tempList[i].getAbsolutePath(),list);
            }
        }
    }
    private boolean isImage(String name) {
        String suffix = name.substring(name.lastIndexOf(".")+1);
        for(ImageType type:ImageType.values()) {
            if(suffix.equalsIgnoreCase(type.toString())) {
                return true;
            }
        }
        return false;

    }
    public boolean openFolder() {
        String path = browseFolder();
        if(path==null|| path.isEmpty()) {
            return false;
        }
        ArrayList<String> arrayList = new ArrayList<String>();
        ergodicImage(path,arrayList);
        return true;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

3、界面 AlbumTreeUI

package imageView.cxyax.ui;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JScrollPane;

public class AlbumTreeUI extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private DefaultMutableTreeNode root;
    public JTree tree;
    private Map<DefaultMutableTreeNode,String> map = new HashMap<>();
    private static final AlbumTreeUI instance = new AlbumTreeUI();
    public Map<DefaultMutableTreeNode,String> getMap() {
        return map;
    }

    public static AlbumTreeUI getInstance() {
        return instance;
    }

    /**
     * Create the panel.
     */
    private AlbumTreeUI() {
        root = new DefaultMutableTreeNode("Album");
        DefaultTreeModel model = new DefaultTreeModel(root);
        setLayout(new BorderLayout(0, 0));

        JPanel panel = new JPanel();
        add(panel, BorderLayout.CENTER);
        panel.setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane = new JScrollPane();
        panel.add(scrollPane);
        panel.setPreferredSize(new Dimension(80,520));
        tree = new JTree();
        scrollPane.setViewportView(tree);
        tree.setModel(model);
    }
    public DefaultMutableTreeNode addAlbum(String path) {
         String name = path.substring(path.lastIndexOf(""));
         DefaultMutableTreeNode parent = new DefaultMutableTreeNode(name);
         root.add(parent);
         return parent;
    }
    public void addImage(DefaultMutableTreeNode parent, String path) {
        DefaultMutableTreeNode defaultMutableTreeNode = new DefaultMutableTreeNode(path.substring(path.lastIndexOf("")+1));
        getMap().put(defaultMutableTreeNode, path);
        parent.add(defaultMutableTreeNode);
    }
    public void deleteImage() {
         DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
         if ((selectNode == null) || (selectNode.isRoot())) {
             return;
         }
         DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
         model.removeNodeFromParent(selectNode);
         tree.repaint();
    }
    public String openImage() {
        DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
         if ((selectNode == null) || (selectNode.isRoot())) {
             return null;
         }
         String path = map.get(selectNode);
         return path;
    }

}

ImageDispalyUI

package imageView.cxyax.ui;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class ImageDispalyUI extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public JButton btnNewButton;
    private ImageIcon imageIcon;

    /**
     * Create the panel.
     */
    public ImageDispalyUI(String imagePath) {
        imageIcon = new ImageIcon(imagePath);
        setSize(imageIcon.getIconWidth(),imageIcon.getIconHeight());
        setLayout(new BorderLayout(0, 0));
        btnNewButton = new JButton("");
        btnNewButton.setIcon(imageIcon);
        add(btnNewButton);
    }
    public ImageIcon getImageIcon() {
        return imageIcon;
    }

}

ImageUI

package imageView.cxyax.ui;

import java.awt.Dimension;

import javax.swing.JPanel;

public class ImageUI extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final ImageUI instance = new ImageUI();
    private int positionX = 5;
    private int positionY = 5;

    public static ImageUI getInstance() {
        return instance;
    }
    /**
     * Create the panel.
     */
    private ImageUI() {
        setLayout(null);
    }

    public void addImage(String path) {
        ImageDispalyUI imageDispalyUI = new ImageDispalyUI(path);
        int width = this.getWidth()-80;
        int height = this.getHeight()-80; 
        int imageWidth = imageDispalyUI.getWidth();
        int imageHeight = imageDispalyUI.getHeight();
        imageDispalyUI.setBounds(positionX, positionY, imageWidth,imageHeight);
        int x = imageWidth+positionX;
        int y = imageHeight+positionY;
        if(x<width && y<height) {
            positionX += imageWidth+5;
        }
        if(x>width && y<height) {
            positionX = 5;
            positionY += imageHeight+5;
        }
        if(x>width && y>height) {
            positionY += imageHeight;
            this.setPreferredSize(new Dimension(positionX,positionY));
        }
        this.add(imageDispalyUI);
        this.updateUI();
    }
}

ImageViewFrameUI

package imageView.lyrics.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import imageView.lyrics.service.AlbumService;

public class ImageViewFrameUI {

    private JFrame frame;
    private JMenuItem mntmOpenfolder;
    private AlbumService albumService = new AlbumService();
    private AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance();

    /**
     * Create the application.
     */
    public ImageViewFrameUI() {
        initialize();
        addListener();
        leftPanelListener();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setVisible(true);
        frame.setTitle("Image View");
        frame.setBounds(100, 100, 800, 600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        JMenuItem mntmOpenFile = new JMenuItem("open file");
        mnFile.add(mntmOpenFile);

        mntmOpenfolder = new JMenuItem("open folder");
        mnFile.add(mntmOpenfolder);

        JMenu mnEdit = new JMenu("Edit");
        menuBar.add(mnEdit);

        JMenuItem mntmAdd = new JMenuItem("add");
        mnEdit.add(mntmAdd);

        JMenuItem mntmModify = new JMenuItem("modify");
        mnEdit.add(mntmModify);

        JMenuItem mntmRemove = new JMenuItem("remove");
        mnEdit.add(mntmRemove);

        JMenu mnView = new JMenu("View");
        menuBar.add(mnView);

        JMenuItem mntmFind = new JMenuItem("find");
        mnView.add(mntmFind);

        JMenu mnHelp = new JMenu("Help");
        menuBar.add(mnHelp);

        JMenuItem mntmAbout = new JMenuItem("About");
        mnHelp.add(mntmAbout);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane = new JScrollPane();
        frame.getContentPane().add(scrollPane);
        JPanel panel = new JPanel();
        scrollPane.setViewportView(panel);
        panel.setPreferredSize(new Dimension(760,520));
        panel.setLayout(new BorderLayout(0, 0));

        JSplitPane splitPane = new JSplitPane();
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(0.2);
        panel.add(splitPane);
        AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance(); 
        splitPane.setLeftComponent(albumTreeUI);
        ImageUI imageUI = ImageUI.getInstance();
        splitPane.setRightComponent(imageUI);
    }

    private void addListener() {
        mntmOpenfolder.addActionListener(event -> {
            albumService.openFolder();
        });

    }
    private void leftPanelListener() {
        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String imagePath = albumTreeUI.openImage(); 
                System.out.println(imagePath);
            }
        }; 
        albumTreeUI.tree.addMouseListener(mouseAdapter);
    }
}

4.util

package imageView.cxyax.util;

import net.coobird.thumbnailator.Thumbnails;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

 */
public class ResizeImage {
    public static void main(String[] args) {
        ResizeImage.generateFixedSizeImage("D:download毕业图片IMG_3303.CR2","thumbnail3.jpg");
    }

    /**
     * 使用给定的图片生成指定大小的图片
     */
    public static String generateFixedSizeImage(String inputPath,String outputPath){
        try {
            InputStream inputStream = new FileInputStream(inputPath);
            Thumbnails.of(inputStream).size(80,80).toFile(outputPath);
            return outputPath;
        } catch (IOException e) {
            System.out.println("原因: " + e.getMessage());
        }
        return "";
    }
}

五、效果

初始界面


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第4
张图片


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第5
张图片


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第6
张图片


用JavaSwing制作简易电子相册
-程序员阿鑫-带你一起秃头
-第7
张图片

以上是《用Java Swing制作简易电子相册》文章的全部内容,感谢您的支持!

以上就是《用Java Swing制作简易电子相册》文章的全部内容了!

版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。
版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!

-- 展开阅读全文 --
这篇文章最后更新于2020-7-7,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
最新PHP在线客服系统IM即时通讯聊天源码微信公众号小程序H5APP网页端在线客服
« 上一篇
微信群二维码活码生成管理系统源码
下一篇 »

发表评论

HI ! 请登录
注册会员,享受下载全站资源特权。
登陆
上号,带你一起秃头!

热门文章

最新文章

标签