2016-01-15 48 views
0

我一直在爲這個問題苦苦掙扎了一小會兒,我可以使用一般活動偵聽器切換圖片,但無法爲可點擊區域選擇區域以允許開關。我希望創建一個邊界的矩形,使我有一個可點擊的區域來更改圖片。我嘗試過,但我不確定如何設置一個動作監聽器在jpanel的特定區域工作。任何幫助將不勝感激,謝謝!我需要在圖片的範圍內創建可點擊的圖片。然後我需要圖片在文件夾中的圖片進行切換

public class drawPictures { 
Random random = new Random(); 
int one = random.nextInt(1200)+1; 
int two = random.nextInt(600)+1; 

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

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

public class ImageViewPane extends JPanel { 

    private ImagePane imagePane; 
    private File[] fileList; 
    private int currentIndex = -1; 

    public ImageViewPane() { 

     fileList = new File("/Di/rec/tory").listFiles(new FileFilter() { 
      @Override 
      public boolean accept(File pathname) { 
       return pathname.isFile(); 
      } 
     }); 

     imagePane = new ImagePane(); 
     imagePane.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent e) { 

     Rectangle bounds = new Rectangle(one, two, 100, 100); 
     if (bounds.contains((e).getPoint())){ 
      // Image was clicked... 
      currentIndex++; 
      if (currentIndex >= fileList.length) { 
       currentIndex = 0; 
      } 
      nextImage(); 
      } 

     setLayout(new GridBagLayout()); 
     add(imagePane); 

     nextImage(); 
      }});} 

    public void nextImage() { 
     if (fileList != null && fileList.length > 0) { 
      currentIndex++; 
      if (currentIndex < 0 || currentIndex >= fileList.length) { 
       currentIndex = 0; 
      } 
      Image image = null; 
      /* 
       Because I don't know the contents of the folder, this is a little 
       more complicated then it really needs to be. 

       If you know the file is an image, you can simply use ImageIO.read(file) 
      */ 
      while (image == null && currentIndex < fileList.length) { 
       System.out.println("Loading next image: " + currentIndex); 
       try { 
        ImageInputStream iis = ImageIO.createImageInputStream(fileList[currentIndex]); 
        if (iis != null) { 
         Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis); 
         if (imageReaders != null && imageReaders.hasNext()) { 
          ImageReader imageReader = imageReaders.next(); 
          imageReader.setInput(iis); 
          image = imageReader.read(0); 
         } else { 
          currentIndex++; 
         } 
        } else { 
         currentIndex++; 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
        currentIndex++; 
       } 
      } 
      imagePane.setImage(image); 
      invalidate(); 
      repaint(); 
     } 
    } 
} 

public class ImagePane extends JPanel { 

    private Image image; 
    private JLabel label; 

    public ImagePane() { 
     setLayout(new GridBagLayout()); 
     label = new JLabel("No image available"); 
     add(label); 
    } 

    public void setImage(Image value) {`` 
     if (image != value) { 
      image = value; 
      label.setVisible(image == null); 
      repaint(); 
     } 
    } 

    @Override 

    public Dimension getPreferredSize() { 
     return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this)+140, image.getHeight(this)+200); 
    } 
    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (image != null) { 
      int width = getWidth(); 
      int height = getHeight(); 
      int x = (width - image.getWidth(this))/2 -500 + one; 
      int y = (height - image.getHeight(this))/2- 300 + two; 
      g.drawImage(image, x, y, this); 


     } 
    } 
} 

}

回答

2

讓我們先從明顯的事情......

你從來沒有真正加入ImagePane任何東西(入手,嘗試將它添加它被點擊之後,卻怎麼做它獲得點擊,如果它不添加任何東西?)

//... 
public ImageViewPane() { 
    //... 
    imagePane = new ImagePane(); 
    imagePane.addMouseListener(new MouseAdapter() { 
     @Override 
     public void mouseClicked(MouseEvent e) { 
      //... 
     } 
    }); 

    // And... nothing 
} 

有很多在MouseListener去上真的不需要在那裏......

imagePane.addMouseListener(new MouseAdapter() { 
    @Override 
    public void mouseClicked(MouseEvent e) { 

     Rectangle bounds = new Rectangle(one, two, 100, 100); 
     if (bounds.contains((e).getPoint())) { 
      // Image was clicked... 
      currentIndex++; 
      if (currentIndex >= fileList.length) { 
       currentIndex = 0; 
      } 
      nextImage(); 
     } 

     setLayout(new GridBagLayout()); 
     add(imagePane); 

     nextImage(); 
    } 
}); 

您的通話nextImage至少一次,如果不是兩次。一次,如果用戶在你的可信框內單擊,並在方法結束時單擊一次。儘管nextImage這樣做,你也增加了currentIndex的價值。你似乎也嘗試添加imagePane到容器... ...再次

這可以簡化到...

imagePane.addMouseListener(new MouseAdapter() { 
    @Override 
    public void mouseClicked(MouseEvent e) { 
     Rectangle bounds = new Rectangle(one, two, 100, 100); 
     if (bounds.contains((e).getPoint())) { 
      // Image was clicked... 
      nextImage(); 
     } 
    } 
}); 

接下來,你nextImage方法...

public void nextImage() { 
    if (fileList != null && fileList.length > 0) { 
     currentIndex++; 
     if (currentIndex < 0 || currentIndex >= fileList.length) { 
      currentIndex = 0; 
     } 
     Image image = null; 
     /* 
     Because I don't know the contents of the folder, this is a little 
     more complicated then it really needs to be. 

     If you know the file is an image, you can simply use ImageIO.read(file) 
     */ 
     while (image == null && currentIndex < fileList.length) { 
      System.out.println("Loading next image: " + currentIndex); 
      try { 
       ImageInputStream iis = ImageIO.createImageInputStream(fileList[currentIndex]); 
       if (iis != null) { 
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis); 
        if (imageReaders != null && imageReaders.hasNext()) { 
         ImageReader imageReader = imageReaders.next(); 
         imageReader.setInput(iis); 
         image = imageReader.read(0); 
        } else { 
         currentIndex++; 
        } 
       } else { 
        currentIndex++; 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
       currentIndex++; 
      } 
     } 
     imagePane.setImage(image); 
     invalidate(); 
     repaint(); 
    } 
} 

好吧,其實這是不壞的「雕蟲小技」,圍繞閱讀圖像可以被過濾掉那些你知道文件不是簡單的文件

fileList = new File("https://stackoverflow.com/a/directory/somewhere").listFiles(new FileFilter() { 
    @Override 
    public boolean accept(File pathname) { 
     return pathname.isFile() 
       && (pathname.getName().toLowerCase().endsWith(".jpg") 
       || pathname.getName().toLowerCase().endsWith(".bmp") 
       || pathname.getName().toLowerCase().endsWith(".png") 
       || pathname.getName().toLowerCase().endsWith(".gif")); 
    } 
}); 

讓我們假裝我們生活在一個擴展實際上意味着什麼的世界。你同樣可以嘗試,並在這裏閱讀圖像和丟棄它,如果它不是一個圖像,但是這是可悲的耗費時間......

這允許使用,使nextImage更像......

public void nextImage() { 
    if (fileList != null && fileList.length > 0) { 
     currentIndex++; 
     if (currentIndex < 0 || currentIndex >= fileList.length) { 
      currentIndex = 0; 
     } 
     try { 
      Image image = ImageIO.read(fileList[currentIndex]); 
      imagePane.setImage(image); 
      invalidate(); 
      repaint(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

現在,就個人而言,我有File S IN一List,每次File未能產生一個Image,我會從List刪除它,但是這是我

添加最後,你還應該添加...

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

ImageViewPane類,這將允許你收拾它周圍的框架(我一直在測試過程中失去了我的「神奇」方因爲窗口是小)

我不完全知道是什麼這是試圖做...

int x = (width - image.getWidth(this))/2 - 500 + one; 
int y = (height - image.getHeight(this))/2 - 300 + two; 

但是,像...

int x = one + ((100 - image.getWidth(this))/2); 
int y = two + ((100 - image.getHeight(this))/2); 

將讓你的「神奇」的方框內居中圖像...

最後,因爲一堆出來的上下文代碼很難放回原位...

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.GridBagLayout; 
import java.awt.Image; 
import java.awt.Rectangle; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.io.File; 
import java.io.FileFilter; 
import java.io.IOException; 
import java.util.Iterator; 
import java.util.Random; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.imageio.ImageIO; 
import javax.imageio.ImageReader; 
import javax.imageio.stream.ImageInputStream; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class DrawPictures { 

    Random random = new Random(); 
    int one = random.nextInt(1200) + 1; 
    int two = random.nextInt(600) + 1; 

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

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

    public class ImageViewPane extends JPanel { 

     private ImagePane imagePane; 
     private File[] fileList; 
     private int currentIndex = -1; 

     public ImageViewPane() { 

      fileList = new File("...").listFiles(new FileFilter() { 
       @Override 
       public boolean accept(File pathname) { 
        return pathname.isFile() 
          && (pathname.getName().toLowerCase().endsWith(".jpg") 
          || pathname.getName().toLowerCase().endsWith(".bmp") 
          || pathname.getName().toLowerCase().endsWith(".png") 
          || pathname.getName().toLowerCase().endsWith(".gif")); 
       } 
      }); 

      imagePane = new ImagePane() { 
       @Override 
       protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        g.setColor(Color.BLACK); 
        g.drawRect(one, two, 100, 100); 
       } 

      }; 
      imagePane.addMouseListener(new MouseAdapter() { 
       @Override 
       public void mouseClicked(MouseEvent e) { 
        Rectangle bounds = new Rectangle(one, two, 100, 100); 
        if (bounds.contains((e).getPoint())) { 
         // Image was clicked... 
         nextImage(); 
        } 
       } 
      }); 
      setLayout(new BorderLayout()); 
      add(imagePane); 
     } 

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

     public void nextImage() { 
      if (fileList != null && fileList.length > 0) { 
       currentIndex++; 
       if (currentIndex < 0 || currentIndex >= fileList.length) { 
        currentIndex = 0; 
       } 
       try { 
        Image image = ImageIO.read(fileList[currentIndex]); 
        imagePane.setImage(image); 
        invalidate(); 
        repaint(); 
       } catch (IOException ex) { 
        ex.printStackTrace(); 
       } 
      } 
     } 
    } 

    public class ImagePane extends JPanel { 

     private Image image; 
     private JLabel label; 

     public ImagePane() { 
      setLayout(new GridBagLayout()); 
      label = new JLabel("No image available"); 
      add(label); 
     } 

     public void setImage(Image value) { 
      if (image != value) { 
       image = value; 
       label.setVisible(image == null); 
       repaint(); 
      } 
     } 

     @Override 

     public Dimension getPreferredSize() { 
      return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this) + 140, image.getHeight(this) + 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      if (image != null) { 
       int width = getWidth(); 
       int height = getHeight(); 
       int x = one + ((100 - image.getWidth(this))/2); 
       int y = two + ((100 - image.getHeight(this))/2); 
       g.drawImage(image, x, y, this); 

      } 
     } 
    } 
}