单击箭头键(keylistener)时图片不刷新

时间:2013-11-15 01:40:31

标签: java image swing slideshow keylistener

我坐着卡住,点击箭头键时我的照片不会加载。只显示第一张照片。然后没有更多的事情发生。我希望能够通过单击箭头键更改我的文件夹中的图片。这是代码。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;


class MyPanel extends JPanel implements KeyListener {
//public Image [] walkable;

    public Image walkable;
    int i = 0;
    public char c = 'e';
    public String p = "no";
    public ImageIcon icon;
//for (int s=0;s<3;s++){
//  ImageIcon  p[s] = ImageIcon("002.jpg");
//  }
//ImageIcon icon = new ImageIcon(p);

//ImageIcon  icon = ImageIcon("001.jpg");
    //ImageIcon icon = new ImageIcon();
    public MyPanel() {
        this.setPreferredSize(new Dimension(500, 500));

        String path = ".";
        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();

        if (i < listOfFiles.length) {
            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                if (files.endsWith(".jpg") || files.endsWith(".JPG") || files.endsWith(".png") || files.endsWith(".PNG")) {
                    ImageIcon icon = new ImageIcon(files);
                    walkable = icon.getImage();
       // return icon;
                }
            }
        }
        addKeyListener(this);
    }

    public void addNotify() {
        super.addNotify();
        requestFocus();
    }

    public void paintComponent(Graphics g) {
    //g.clearRect(0, 0, getWidth(), getHeight());
        //g.drawString("the key that pressed is " + c, 250, 250);
        //g.drawString("the key that pressed is " + p, 400, 250);
        g.drawImage(walkable, 0, 0, this);
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        c = e.getKeyChar();

        int keyCode = e.getKeyCode();
        switch (keyCode) {
            case KeyEvent.VK_UP:
                // handle up
                break;
            case KeyEvent.VK_DOWN:
                // handle down
                break;
            case KeyEvent.VK_LEFT:
                i = i - 1;
                //walkable = icon.getImage();
                break;
            case KeyEvent.VK_RIGHT:
                i = i + 1;
                //walkable = icon.getImage();
                break;

        }
        repaint();
    }

    public static void main(String[] s) {

        JFrame f = new JFrame();
        f.getContentPane().add(new MyPanel());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:2)

您正在更改i的状态,但是您没有对其进行任何操作,walkable从未在构造函数中加载时发生变化...

我还建议使用Key Bindings而不是KeyListener因为KeyListener不会遇到同样的焦点问题

已更新建议

首先,我过滤文件列表,以便列表中只存在有效的图像文件。看一下File#listFiles(FileFilter),它将允许在生成文件列表时应用过滤器。

其次,我会将类可用的文件列表作为实例变量,这样您就可以在需要时访问。

第三,我会使用ImageIO.read来阅读图像。它支持大量文件格式,立即加载图像并在出现问题时抛出IOException,而不是像ImageIcon那样无声地失败。请查看http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html了解更多详情

以下是提到的想法的一个非常简单的例子。它在Event Dispatching Thread的上下文中加载图像,因此在大图像上,它将“停止”您的程序。请特别关注Concurrency in SwingSwingWorker,了解有关如何实现这一目标的建议......

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ImageWalker extends JPanel {

    public static void main(String[] args) {
        new ImageWalker();
    }

    public ImageWalker() {
        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 MyPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MyPanel extends JPanel {

        public Image walkable;
        private int i = 0;
        private File[] listOfFiles;

        public MyPanel() {

            String path = ".";
            File folder = new File(path);
            listOfFiles = folder.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName().toLowerCase();
                    return name.endsWith("png") || name.endsWith("jpg");
                }
            });

            if (listOfFiles != null && listOfFiles.length > 0) {
                loadCurrent();
            }

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "next");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");

            am.put("next", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (listOfFiles != null && listOfFiles.length > 0) {
                        i--;
                        if (i < 0) {
                            i = listOfFiles.length - 1;
                        }
                        loadCurrent();
                    }
                }
            });
            am.put("right", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (listOfFiles != null && listOfFiles.length > 0) {
                        i++;
                        if (i >= listOfFiles.length) {
                            i = 0;
                        }
                        loadCurrent();
                    }
                }
            });

        }

        protected void loadCurrent() {

            if (listOfFiles != null && listOfFiles.length > 0) {
                File file = listOfFiles[i];
                try {
                    walkable = ImageIO.read(file);
                    repaint();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(walkable, 0, 0, this);
        }
    }
}