制作图像查看器时出错 [英] Error in making image viewer

查看:187
本文介绍了制作图像查看器时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是在尝试使用Java创建一个简单的图像查看器。它包括一个标签和三个按钮。其中两个按钮用作导航的左右箭头键,第三个按钮用于选择目录的打开按钮。但是,当我单击打开时,只查看第一个JPG图像,并且该图像太未缩放。如果我单击前进按钮,则不会发生导航。

I am actually trying to make a simple image viewer using Java. It includes a label and three buttons. Two of these buttons act as left and right arrow keys for navigation and 3rd is an open button to select a directory. However, when I click on open only the first JPG image is viewed and that too unscaled . If I click on the forward button, the navigation does not happen.

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;


public class picframe extends Thread implements ActionListener
{
  JTree tr;
  JScrollPane jsp;
  JFrame f;
  JButton b1,b2,b3;
  JLabel lab;
  File fl;
  File[] flist;
  ImageIcon ig;
  int k,j=0;
  FileDialog fdial;
  String str;

  picframe()
  {
    f=new JFrame("My Frame");
    f.setVisible(true);
    f.setLayout(null);


    lab=new JLabel();
    lab.setBounds(100,50,1166,500);
    f.add(lab);

    b1=new JButton(" <| ");
    b1.setBounds(486,600,100,30);
    b1.setEnabled(false);
    f.add(b1);
    b1.addActionListener(this);



    b2=new JButton(" |> ");
    b2.setBounds(786,600,100,30);
    f.add(b2);
    b2.setEnabled(false);
    b2.addActionListener(this);

    b3=new JButton("Open");
    b3.setBounds(633,650,100,30);
    f.add(b3);
    b3.addActionListener(this);

    f.pack();
    f.setSize(1366,768);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public void actionPerformed(ActionEvent ae)
  {

    if(ae.getActionCommand().equals("Open"))
    {
      FileDialog fdial=new FileDialog(f,"Open Box",FileDialog.LOAD);
      fdial.setSize(300,300);
      fdial.setVisible(true);
      str=fdial.getDirectory();
      fl=new File(str);
      flist=fl.listFiles();
      b2.setEnabled(true);


      rat:while(j<flist.length)
      {
        if(flist[j].isFile())
        {
          if(flist[j].getName().toLowerCase().endsWith(".jpg"))
          {
            ig=new ImageIcon(fdial.getDirectory()+flist[j].getName());
            lab.setIcon(ig);
            break rat;

          }
        }

        j++;
      }


    }

    if(ae.getActionCommand().equals("<|"))
    {
      --j;

      if(j+1!=0)
      {
        bat:while(j<flist.length)
        {
          if(flist[j].isFile())
          {
            if(flist[j].getName().toLowerCase().endsWith(".jpg"))
            {
              ig=new ImageIcon(fdial.getDirectory()+flist[j].getName());
              lab.setIcon(ig);
              b1.setEnabled(true);
              break bat;
            }
          }

          j--;
        }
      }

      if(j<0 || !flist[j].isFile())
      {
        lab.setText("no image");
      }

      if(ae.getActionCommand().equals("|>"))
      {
        ++j;

        if(j-1!=flist.length)
        {
          cat:while(j<flist.length)
          {
            if(flist[j].isFile())
            {
              if(flist[j].getName().toLowerCase().endsWith(".jpg"))
              {
                ig=new ImageIcon(fdial.getDirectory()+flist[j].getName());
                lab.setIcon(ig);
                b1.setEnabled(true);
                break cat;

              }
            }

            j++;
          }
        }

        if(j>flist.length || !flist[j].isFile())
        {
          lab.setText("no image");
        }
      }

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


}


推荐答案


而且太未缩放

and that too unscaled

是什么让你觉得它应该是另外的?? Swing不提供任何自动缩放其内容的组件(我的头顶),这样你就必须为自己做好准备。看一下以前关于这个主题的问题,找出一些解决方案

And what makes you think it should be otherwise?? Swing doesn't provide any components (of the top of my head) that do automatically scale its contents, this, you're going to have to work out for your self. Take a look at these previous questions on the subject for some solutions

  • Java: maintaining aspect ratio of JPanel background image
  • Jpanel resize on repaint

更新#1

您还有其他问题 f.setLayout(null) ; ,这样做意味着您突然负责管理组件的大小,因此当您加载新图像时,它的大小可能与以前不同,但您似乎没有做任何尝试更新图片标签......

You other problems is this f.setLayout(null);, doing this means you suddenly become responsible for managing the size of components, so when you load a new image, it's size may be different from the previous, but you don't seem to make any attempt to update the image label...

更新#2

flist [j] .getPath()会给你一个更好的结果 fdial.getDirectory()+ flist [j] .getName()尽可能缺少路径分隔符;)

flist[j].getPath() will give you a better result then fdial.getDirectory()+flist[j].getName() as you may be missing the path separator ;)

更新#3

这是一个工作示例...没有缩放

Here's a working example...without scaling

public class BetterBrowser {

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

    public BetterBrowser() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new BrowserPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class BrowserPane extends JPanel {

        private FileModel fileModel;
        private JButton open;
        private JButton next;
        private JButton prev;

        private JLabel image;

        public BrowserPane() {
            fileModel = new FileModel();
            setLayout(new BorderLayout());

            JToolBar tb = new JToolBar();
            tb.add((open = new JButton(new OpenAction(fileModel))));

            add(tb, BorderLayout.NORTH);

            JPanel navPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
            navPane.add((prev = new JButton(new PrevAction(fileModel))));
            navPane.add((next = new JButton(new NextAction(fileModel))));

            add(navPane, BorderLayout.SOUTH);
            add(new JScrollPane((image = new JLabel())));

            fileModel.addListDataListener(new ListDataListener() {
                @Override
                public void intervalAdded(ListDataEvent e) {
                }

                @Override
                public void intervalRemoved(ListDataEvent e) {
                }

                @Override
                public void contentsChanged(ListDataEvent e) {
                    if (e.getIndex0() == -1 && e.getIndex1() == -1) {
                        File file = (File) fileModel.getSelectedItem();
                        try {
                            ImageIcon icon = new ImageIcon(ImageIO.read(file));
                            image.setIcon(icon);
                        } catch (IOException exp) {
                            exp.printStackTrace();;
                            image.setIcon(null);
                        }
                    }
                }
            });
        }

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

    }

    public class OpenAction extends AbstractAction {

        private FileModel model;

        public OpenAction(FileModel model) {
            this.model = model;
            putValue(NAME, "Open");
        }

        public FileModel getModel() {
            return model;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.setMultiSelectionEnabled(false);
            switch (fc.showOpenDialog((Component) e.getSource())) {
                case JFileChooser.APPROVE_OPTION:
                    File folder = fc.getSelectedFile();
                    File[] files = folder.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            String name = pathname.getName().toLowerCase();
                            return name.endsWith(".jpg")
                                            || name.endsWith(".png")
                                            || name.endsWith(".gif");
                        }

                    });

                    model.removeAllElements();

                    FileModel model = getModel();
                    for (File file : files) {
                        model.addElement(file);
                    }

                    if (model.getSize() > 0) {
                        model.setSelectedItem(model.getElementAt(0));
                    }
                    break;
            }
        }

    }

    public class FileModel extends DefaultComboBoxModel<File> {
    }

    public abstract class AbstractNavigationAction extends AbstractAction {

        private FileModel fileModel;
        private int direction;

        public AbstractNavigationAction(FileModel fileModel, int direction) {
            this.fileModel = fileModel;
            this.direction = direction;
            fileModel.addListDataListener(new ListDataListener() {
                @Override
                public void intervalAdded(ListDataEvent e) {
                    updateState();
                }

                @Override
                public void intervalRemoved(ListDataEvent e) {
                    updateState();
                }

                @Override
                public void contentsChanged(ListDataEvent e) {
                    updateState();
                }

            });
            updateState();
        }

        protected void updateState() {
            setEnabled(getFileModel().getSize() > 0);
        }

        public FileModel getFileModel() {
            return fileModel;
        }

        public int getDirection() {
            return direction;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            FileModel model = getFileModel();
            if (model.getSize() > 0) {
                File file = (File) model.getSelectedItem();
                int index = model.getIndexOf(file);

                index += direction;
                if (index < 0) {
                    index = model.getSize() - 1;
                } else if (index >= model.getSize()) {
                    index = 0;
                }
                file = model.getElementAt(index);
                model.setSelectedItem(file);
            }
        }

    }

    public class PrevAction extends AbstractNavigationAction {

        public PrevAction(FileModel fileModel) {
            super(fileModel, -1);
            putValue(NAME, "< Previous");
        }

    }

    public class NextAction extends AbstractNavigationAction {

        public NextAction(FileModel fileModel) {
            super(fileModel, 1);
            putValue(NAME, "Next >");
        }

    }

}

这篇关于制作图像查看器时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆