有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java图像未从列表重新绘制<path>

我试图从指定路径加载图像,文件列表存储在列表中<>;。 第一次初始化图像时,它会显示,但当我试图显示包含文件列表的列表实例中的下一个图像时,不会重新绘制图像。 问题是我第一次在构造函数中初始化映像时覆盖了 新的映像,现在在构造函数外部第一次初始化映像的位置我不知道

我的代码:

 public void nextImage(int cnt)
    {                   
        System.out.println(cnt);

        if (cnt < imageFiles.size()) 
        {
            System.out.println(imageFiles.size());
            try 
            {                   
                bg = ImageIO.read(new File((imageFiles.get(cnt)).toString()));

                scaled = getScaledInstanceToFit(bg, new Dimension(600, 600));
                setBackground(Color.BLACK);

            } 
            catch(Exception e) 
            {
                e.printStackTrace();
            }
        }

        MouseHandler handler = new MouseHandler();
        addMouseListener(handler);
        addMouseMotionListener(handler);           
        System.out.println(cnt);            
        System.out.println(imageFiles.get(cnt).toString());         
    }

菜单项单击代码:

JMenuItem mntmRestoreImage = new JMenuItem("Next Image");

        final ImagePane st = new ImagePane();           

        mntmRestoreImage.addActionListener(new ActionListener() 
        {                       
        @Override
            public void actionPerformed(ActionEvent arg0) 
            {               
               st.nextImage(k);
               k++;     
            }
        });

        mnEdit.add(mntmRestoreImage);

类别代码及;建造商:

private BufferedImage bg;
        private BufferedImage scaled;
java.util.List<Path> imageFiles= getFilesFromDirectory(FileSystems.getDefault().getPath("D:\\New folder")); 


 public ImagePane() 
        {
try 
            {
                bg = ImageIO.read(getClass().getResource("/images/src11.jpg"));
                scaled = getScaledInstanceToFit(bg, new Dimension(600, 600));
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
}

counter also increments, now the code inside ImagePane() constructor overwrites the image of nextImage() function, so idea what happen out in this code ??

any suggestion ?


共 (2) 个答案

  1. # 1 楼答案

    这不是答案,但我无法将那么多代码粘贴到注释中

    我会将您的代码更改为类似于这段代码的代码。这将图像加载与gui更新逻辑分离(如添加鼠标手柄等,我只粘贴了图像加载代码)

    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Arrays;
    import java.util.Iterator;
    import javax.imageio.ImageIO;
    
    public class ImageLoader
    {
        public static class ImageContainer
        {
            BufferedImage bg = null;
    
            BufferedImage scaled;
        }
    
        Iterator<File> imageFiles = Arrays.asList(
                new File("D:\\New folder").listFiles()).iterator();
    
        public ImageContainer nextImage(Dimension dimensionToFit) throws Exception
        {
            ImageContainer c = new ImageContainer();
            if (imageFiles.hasNext())
            {
                    File file = imageFiles.next();
                                        //you might not need this, if only images are in this directory
                    if(file.isDirectory())
                        return null;
                    c.bg = ImageIO.read(file);
                    c.scaled = getScaledInstanceToFit(c.bg, dimensionToFit);
                    return c;
            }
            else
                return null;
        }
    
        private BufferedImage getScaledInstanceToFit(BufferedImage bg,
                Dimension dimensionToFit)
        {
            //do the risizing
        }
    }
    

    但这还没有优化

  2. # 2 楼答案

    我想我有一个完美的解决方案给你!我为你写了一个小程序,这样更容易理解

    首先,我有一个方法让您检查文件是否为图片:

    public Stack<File> getFilesInFolder(String startPath) {
        File startFolder = new File(startPath);
        Stack<File> picturestack = new Stack<File>();
    
        String extension;
        int dotindex;
    
        // Go through the folder
        for (File file : startFolder.listFiles()) {
            extension = "";
            dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
    
            if (dotindex > 0) {
                extension = file.getName().substring(dotindex + 1);
    
                // Iterate all valid file types and check it
                for (String filetype : validpicturetypes) {
                    if (extension.equals(filetype)) {
                        picturestack.add(file);
                    }
                }
            }
        }
        return picturestack;
    }
    

    很简单!取下文件夹并迭代他的文件。获取文件的扩展名并检查它是否为有效的文件类型。在代码开头定义数组中的文件类型

    String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
    

    最后,我将每个文件放入堆栈。请记住将堆栈填充到变量中,不要多次读取文件,因为您会遇到与以前相同的问题:

    Stack<File> pictures = getFilesInFolder("C:\\Users\\Admin\\Desktop");
    

    在那之后,为你的物品使用一个动作!在我的例子中我没有太多,你必须把你的方法放进去

    Action nextpictureaction = new AbstractAction("Next Picture") {
        private static final long serialVersionUID = 2421742449531785343L;
    
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!pictures.isEmpty()) {
                System.out.println(pictures.pop().getName());
            }
        }
    };
    

    在jmen中添加动作并设置帧的属性

    /*
     * Add Components to Frame
     */
    setJMenuBar(menubar);
    menubar.add(toolsmenu);
    toolsmenu.add(nextpictureaction);
    
    /*
     * Frame Properties
     */
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationByPlatform(true);
    setSize(1000, 700);
    setTitle("PictureEditor");
    setVisible(true);
    

    最后用invokeLater方法执行你的程序

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PictureEditor();
            }
        });
    }
    

    总结

    基本上你需要一个东西来迭代,因为像integer这样的值并没有以你喜欢的方式保存。在我的示例中,我使用了一个堆栈,并在开始时保存其中的所有图片。重要的是,如果使用或完成了图片,则必须将其删除(使用stack.pop()作为堆栈)。我没有找到一种方法,可以检查文件是否为图片(如果是ImageIO捕获,则为坏文件)。我写了一个方法,如果你想你可以使用它