创建包含图像的可选jpanel的jpanel

时间:2011-10-21 00:59:37

标签: java image swing arraylist jpanel

将一些图像从站点保存到ArrayList后我尝试创建一个jpanel,它将在带有滚动窗格的单独jpanel中显示所有这些图像,以便我可以向每个图像添加动作事件。然后,用户可以选择带有相关图片的jpanel,然后单击“复制”按钮将该图像保存到剪贴板。

以下代码可以正常添加一张图片:

    picHolder = new JPanel();
    picHolder.setSize(50,450);
    picHolder.setBackground(Color.white);

    Icon testicon = new ImageIcon(imageList.get(0));
    JPanel test = new JPanel();
    JLabel testLabel = new JLabel();
    testLabel.setIcon(testicon);

    test.add(testLabel);
    picHolder.add(test);

然而,当我尝试使用以下循环在面板中创建面板时:

    panelArray = new JPanel[imageList.size()];
    labelArray = new JLabel[imageList.size()];
    imageArray = new ImageIcon[imageList.size()]; 


   for (int x=0; x>imageList.size(); x++) {

        imageArray[x] = new ImageIcon(imageList.get(x));


        panelArray[x] = new JPanel();
        panelArray[x].setBackground(Color.red);

        labelArray[x] = new JLabel();
        labelArray[x].setIcon(imageArray[x]);

        panelArray[x].setLayout(new FlowLayout());
        panelArray[x].add(labelArray[x]);
        picHolder.add(panelArray[x]);
        picHolder.validate();
        picHolder.repaint();

    }

我只得到一个空白的屏幕。我试过移动各种元素然而我看不出我做错了什么。如果有人有任何建议或者可能是实现我的目标的另一种方式,我们将不胜感激。

修改
SSCCE

package scrollbartester;

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.Selector;

import java.net.*;

import javax.imageio.*;

import java.util.ArrayList;
import java.awt.*;
import java.awt.Event;
import javax.swing.*;

public class ScrollBarTester {

    ArrayList<Image> imageList = new ArrayList<Image>() ;
    URL url;


    public ArrayList ripPics() {

            String fullST = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=fish&x=0&y=0";

    try {

            Document doc = Jsoup.connect(fullST).timeout(10*1000).get();
            Elements jpgs = doc.select("img[src$=.jpg]");
            Element pictest = jpgs.get((jpgs.size()-1));
            System.out.println(pictest);

            for (int countPics = 0; countPics < jpgs.size(); countPics++) {

                Element currentPic = jpgs.get(countPics);

                String currentPicString = currentPic.toString();
                System.out.println(currentPicString);
                int startofAddress = currentPicString.indexOf("http:");
                int endofAddress = (currentPicString.indexOf(".jpg") + 4);
                String urlOfImage = currentPicString.substring(startofAddress, endofAddress);

            url = new URL(urlOfImage);
            Image currentImage = ImageIO.read(url);
            imageList.add(currentImage);

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

            return imageList;
    }




    public static void main(String[] args) {

        PicRipper ripper = new PicRipper();
        ArrayList<Image> imageList = ripper.ripPics();

        System.out.println(imageList.size());



        JScrollPane scrollPane;


        JFrame main = new JFrame();
        main.setSize(50, 500);
        main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);



        JPanel picHolder = new JPanel();
        picHolder.setSize(450,450);
        picHolder.setBackground(Color.white);

        //Icon testicon = new ImageIcon(imageList.get(0));
        //JPanel test = new JPanel();
        //JLabel testLabel = new JLabel();
        //testLabel.setIcon(testicon);

        //test.add(testLabel);
        //picHolder.add(test);


        JPanel [] panelArray = new JPanel[imageList.size()];
        JLabel [] labelArray = new JLabel[imageList.size()];
        ImageIcon [] imageArray = new ImageIcon[imageList.size()]; 

       for (int x=0; x>imageList.size(); x++) {

            imageArray[x] = new ImageIcon(imageList.get(x));


            panelArray[x] = new JPanel();
            panelArray[x].setBackground(Color.red);

            labelArray[x] = new JLabel();
            labelArray[x].setIcon(imageArray[x]);

            panelArray[x].setLayout(new FlowLayout());
            panelArray[x].add(labelArray[x]);
            picHolder.add(panelArray[x]);
            picHolder.validate();
            picHolder.repaint();


        }


        scrollPane = new JScrollPane(picHolder);


        main.getContentPane().add(BorderLayout.CENTER, scrollPane);
        main.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:4)

例如,使用JList的SSCCE - 可以容纳ImageIcons:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class PicStrip extends JPanel {
   public static final String[] IMAGE_URLS = {
         "http://upload.wikimedia.org/wikipedia/commons/6/63/Lagavulin_-_entrance.JPG",
         "http://upload.wikimedia.org/wikipedia/commons/1/1d/Parliament-Ottawa_edit1.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/b/b0/100OLYMP1.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/1/17/Arpino_panorama.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/a/ad/Cegonha_alsaciana.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/1/18/Eau_transparente_naturelle.JPG",
         "http://upload.wikimedia.org/wikipedia/commons/4/4d/FA-18F_Breaking_SoundBarrier.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/5/58/PuntadelEste.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/3/3c/Punta_Gorda_Belize-gm.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/6/64/Yungangshiku.JPG",
         "http://upload.wikimedia.org/wikipedia/commons/e/e2/Wheel_of_Konark%2C_Orissa%2C_India.JPG",
         "http://upload.wikimedia.org/wikipedia/commons/1/16/Muretto_a_secco.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/3/31/Mercedes_AMG_CLS_55_-_Demonstration_of_drifting_1a_1280x960.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/d/d3/Cascade_carieul_1280x960.jpg",
         "http://upload.wikimedia.org/wikipedia/commons/1/17/Bobbahn_ep.jpg"
         };

   private ImageIcon[] icons = new ImageIcon[IMAGE_URLS.length];
   private DefaultListModel iconListModel = new DefaultListModel();
   private JList iconList = new JList(iconListModel);
   private ImagePanel imagePanel = new ImagePanel();

   public PicStrip() {
      setLayout(new BorderLayout());
      add(new JScrollPane(iconList), BorderLayout.LINE_START);

      add(imagePanel, BorderLayout.CENTER);
      new SwingWorker<Void, ImageIcon>() {

         @Override
         protected Void doInBackground() throws Exception {
            for (String imageUrl : IMAGE_URLS) {
               BufferedImage img = ImageIO.read(new URL(imageUrl));
               img = ImageUtil.createScaledImage(img);
               ImageIcon icon = new ImageIcon(img, imageUrl);
               publish(icon);
            }
            return null;
         }

         protected void process(java.util.List<ImageIcon> chunks) {
            for (ImageIcon icon : chunks) {
               iconListModel.addElement(icon);
            }
         };

         protected void done() {
            Window win = SwingUtilities.getWindowAncestor(PicStrip.this);
            win.pack();
         };

      }.execute();

      iconList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      iconList.addListSelectionListener(new ListSelectionListener() {

         public void valueChanged(ListSelectionEvent e) {
            ImageIcon icon = (ImageIcon)iconList.getSelectedValue();
            final String imageUrl = icon.getDescription();
            new SwingWorker<BufferedImage, Void>() {
               protected BufferedImage doInBackground() throws Exception {
                  return ImageIO.read(new URL(imageUrl));
               };

               @Override
               protected void done() {
                  try {
                     imagePanel.setImage(get());
                  } catch (InterruptedException e) {
                     e.printStackTrace();
                  } catch (ExecutionException e) {
                     e.printStackTrace();
                  }
               }
            }.execute();
         }
      });
   }

   private static void createAndShowGui() {
      PicStrip mainPanel = new PicStrip();

      JFrame frame = new JFrame("PicStrip");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

}

class ImagePanel extends JPanel {
   private static final int PREF_W = (3 * 1280) / 4;
   private static final int PREF_H = (3 * 960) / 4;
   private BufferedImage img = null;

   public void setImage(BufferedImage img) {
      this.img = img;
      repaint();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);

      if (img == null) {
         return;
      }
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g2.drawImage(img, 0, 0, PREF_W, PREF_H, null);

   }

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

class ImageUtil {
   public static final int DEST_WIDTH = 100;
   public static final int DEST_HEIGHT = 75;
   public static final double ASPECT_RATIO = (double) DEST_WIDTH / DEST_HEIGHT;

   public static BufferedImage createScaledImage(BufferedImage original) {
      double origAspectRatio = (double) original.getWidth()
            / original.getHeight();
      double scale = origAspectRatio > ASPECT_RATIO ? 
            (double) DEST_WIDTH / original.getWidth() : 
               (double) DEST_HEIGHT / original.getHeight();            
      int newW = (int) (original.getWidth() * scale);            
      int newH = (int) (original.getHeight() * scale);
      BufferedImage img = new BufferedImage(DEST_WIDTH, DEST_HEIGHT,
            BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = img.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g2.drawImage(original, 0, 0, newW, newH, null);
      g2.dispose();
      return img;
   }
}

编辑1
我已经检查了你的SSCCE - 感谢发布它,我发现的一个问题是错误的for循环。尝试更改此内容:

  for (int x = 0; x > imageList.size(); x++) {

     imageArray[x] = new ImageIcon(imageList.get(x));

     //....
  }

到此:

  for (int x = 0; x < imageList.size(); x++) {

     imageArray[x] = new ImageIcon(imageList.get(x));

     //....
  }

我不确定这是否是您实际程序中的错误,或者它只是SSCCE中的错误,但它很重要。