制作图像查看器时出错

时间:2013-01-12 20:03:17

标签: java image swing events

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

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();
  }


}

2 个答案:

答案 0 :(得分:2)

  

并且那个太未缩放

是什么让你认为应该是其他的? Swing不会提供任何自动扩展其内容的组件(我的头顶),这样你就必须为自己做好准备。关于这个问题,请看一下以前关于某些解决方案的问题

更新了#1

你有其他问题f.setLayout(null);,这意味着你突然要负责管理组件的大小,所以当你加载一个新图像时,它的大小可能与以前不同,但是你没有似乎试图更新图像标签...

更新#2

flist[j].getPath()会给你一个比fdial.getDirectory()+flist[j].getName()更好的结果,因为你可能错过了路径分隔符;)

更新#3

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

enter image description here

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 >");
        }

    }

}

答案 1 :(得分:1)

错误是很多错误我会帮你解决这个错误。

首先,FileDialog fdial;可以放在班级attr上。稍后引用它,但不要创建局部变量。

现在问题在于actionPerformed方法。首先,equals方法无效,因为getActionCommand返回的字符串不对应。

在方法actionPerformed中,您应该在不同的情况之间切换并退出,仅此而已。

用于将当前文件保存在文件列表中的j变量。增加或减少它不应超过数组的范围或ArrayIndexOfBoundException

固定代码是:

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;

  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"))
    {
      fdial=new FileDialog(f,"Open Box",FileDialog.LOAD);
      fdial.setSize(300,300);
      fdial.setVisible(true);
      String str=fdial.getDirectory();
      fl=new File(str);
      flist=fl.listFiles();
      b2.setEnabled(true);
      j = 0;
      if (flist != null)
        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;

            }
          }

          j++;
        }


    }

    if(ae.getActionCommand().equals(" <| "))
    {
      --j;
      if (flist != null)
        if(j<0 )  {
          j = -1;
          lab.setText("no image");
        } else {

          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;
              }
            }

            j--;
          }
        }
    }

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

      if (flist != null)
        if(j>=flist.length){
          j = flist.length;
          lab.setText("no image");
        } else  {
          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;

              }
            }

            j++;
          }
        }
    }



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

}