easier way to implement this code;

Basically I want to display around 50 to 300 images that I will also be allowed to click on to do an event. If I do it this way I have to have 300 imagepanels(which just load a bg image into a panel). Can anyone think of a easier way to do this?

  int counter = 0;
                	      while (rs.next ())
                	      {
                	          String idVal = rs.getString (1);
                	          if(idVal.contentEquals("1") & tokens[6].contentEquals(Level))
                	          {
                	        	  System.out.println(tokens[7]);
                	        	  if(counter == 0)
                	        	  {
                	        	  cards = new ImagePanel(new ImageIcon("tokens[7]" + ".jpg").getImage());
                	        	  cards.setBounds(296, 38, 100, 127);
                	        	  frame.getContentPane().add(cards);
                	        	  cards.addMouseListener(new MouseAdapter() {
                                    	@Override
                                    	public void mouseClicked(MouseEvent arg0) {
                                    		//click event data
                                    		
                                    	}
                                    });
                	        	  counter++;
                	        	  }
                	        	  else if(counter ==1)
                	        	  {
                	        		  cards1 = new ImagePanel(new ImageIcon("tokens[7]" + ".jpg").getImage());
                    	        	  cards1.setBounds(396, 38, 100, 127);
                    	        	  frame.getContentPane().add(cards1);
                    	        	  cards1.addMouseListener(new MouseAdapter() {
                                      	@Override
                                      	public void mouseClicked(MouseEvent arg0) {
                                      		//click event data
                                      		
                                      	}
                                      });
                    	        	  counter++;
                	        	  }
                	        	  else if(counter == 2)
                	        	  {
                	        		  cards2 = new ImagePanel(new ImageIcon("tokens[7]" + ".jpg").getImage());
                    	        	  cards2.setBounds(496, 20, 100, 127);
                    	        	  frame.getContentPane().add(cards2);
                    	        	  cards2.addMouseListener(new MouseAdapter() {
                                        	@Override
                                        	public void mouseClicked(MouseEvent arg0) {
                                        		//click event data
                                        		
                                        	}
                                        });
                    	        	  counter++;
                	        	  }
                	        	  
                	        	  
                	        	  
                	        	  frame.setVisible(true); 

                	          }

Maybe instead of using a class that extends JPanel, have a class that has a getBounds() method that returns the image’s point in space.
Then your MouseListener can loop through each one and test if getBounds().contains(mouseEvent.getPoint());


public class ImageEntity {
    private Image image;
    private Rectangle2D.Double bounds;
    
    public ImageEntity(Image image, Rectangle2D.Double bounds) {
        this.image = image;
        this.bounds = bounds;
    }
    
    public Rectangle2D.Double getBounds() {
        return bounds;
    }
    
    public void draw(Graphics2D g) {
        g.drawImage(image,(int)Math.round(bounds.x),(int)Math.round(bounds.y),(int)Math.round(bounds.width),(int)Math.round(bounds.height));
    }
}

Also why are you using String.contentEquals(CharSequence)? You can just use String.equals(String).

I also have another problem I am trying to load images w/ imagepanel class that loads images into a panel background and I am running into secruity errors. I thought if the images where on the same domain as the applet they would load?

i.e.
ImagePanel cards = new ImagePanel(new ImageIcon(“back.jpg”).getImage());

how might I fix this for an applet?

aused by: java.security.AccessControlException: access denied (java.io.FilePermission back.jpg read)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkRead(Unknown Source)
at sun.awt.SunToolkit.getImageFromHash(Unknown Source)
at sun.awt.SunToolkit.getImage(Unknown Source)
at javax.swing.ImageIcon.(Unknown Source)
at javax.swing.ImageIcon.(Unknown Source)
at foursidecard.strauss.(strauss.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception: java.lang.reflect.InvocationTargetException

Try using

ImagePanel cards = new ImagePanel(new ImageIcon(getClass().getResource(“back.jpg”).getImage());

this should work if you are loading the files from a jar and if I’m not mistaken java will not allow you to read files outside an applet for security reasons. I know this is one of the reasons and I’m pretty sure it’s related to how you are trying to read the file.

Good luck.

tried the above code but it wasn’t seeming to work wasn’t liking the .getimage at the end wanted .getfile . I am using image panel class for loading background panel imageswhich i got from the net.

ImagePanel cards = new ImagePanel(new ImageIcon(“back.jpg”).getImage());

breaks secruity rules for applet i suppose so I am trying to get past that by loading from jar archive?
any other ideas

code of imagepanel class

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageTest {

  public static void main(String[] args) {
    ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());

    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

class ImagePanel extends JPanel {

  private Image img;

  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }

  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }

}

deadly forgot an extra parentheses after the getResource(“back.jpg”) call


new ImageIcon(getClass().getResource("back.jpg")).getImage()

And if that image is in the same server or jar as this class then it should work.

I am sorry I am not understanding I think I need to change the image panel class also which I posted above. The above code says can not convert from image panel to image. or if I try it w/ an image icon it says can not convert from image icon to image.

ImageIcon is not a Type of Image. ImageIcon houses an Image but IS NOT an Image.
The best (and non-n00bish) way is to use javax.imageio.ImageIO.


ImagePanel panel;
try{
    panel = new ImagePanel(ImageIO.read(new URL(getCodeBase(),"back.jpg")));
}
catch(Exception exc) {
    System.out.println("Image not found: " + exc);
    return;
}

I tried the above and it just just would not work : ( . I ended up signing the applet and its working well now : ) maybe l8er down the road ill try to figure out what it doesnt like. ty guys!

Glad to help ;D

could I create an array of class ImagePanel? I know you can have an array of panel? how would that look?

panel1[1] = new ImagePanel(new ImageIcon(getClass().getResource(“back.jpg”)).getImage()); ???

heres the class for ImagePanel

class ImagePanel extends JPanel {

	  private Image img;
	  
	  public ImagePanel(String img) {
	    this(new ImageIcon(img).getImage());
	  }
	  public ImagePanel(Image img) {
	    this.img = img;
	   
	    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
	    setPreferredSize(size);
	    setMinimumSize(size);
	    setMaximumSize(size);
	    setSize(size);
	    setLayout(null);
	  }

	  public void paintComponent(Graphics g) {
	    g.drawImage(img, 0, 0, null);
	  }

	}

Why couldn’t you create an array of ImagePanel? You can create an array of any type :slight_smile:

EDIT: Using JPanel just to draw an image is not very efficient. Look at my first reply.

I like your suggestion but I need to add events so panels work just as fast. My problem when turning it into into an array is I can not add it or proper way to declare.


ImagePanel[] cards1[];

cards1[i] = new ImagePanel[10];

// not sure how to set
cards1[0] = new ImagePanel(new ImageIcon(getClass().getResource("name.jpg")).getImage());

add(cards1[0]);

edit^ I will try your way( i see how you are doing mouse events) but how would that implementation work for above if you don’t mind?

How about using ArrayList?

And for event, your main class would have a nested class that implements ActionListener, and when you get a mouse click, you loop through the array of ImagePanels and test if the point of the click is inside one.


for(ImagePanel ip : panels) {
    if(ip.getBounds().contains(actionEvent.getPoint().x,actionEvent.getPoint().y)) {
        //code when clicking here
    }
}