Results 1 to 3 of 3
  1. #1
    JJay84 is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default How to randomly pick a JLabel that contain image

    I try to create a function that can randomly pick a JLabel(image putting inside the label), however I don't know how to make it work.

    I declare,

    public class capt extends JFrame{

    String [] capth = new String [10];

    public capt(){

    p2=new JPanel();
    p2.setLayout(new GridLayout(1,1));
    image =new JLabel();
    image.setIcon(new ImageIcon("C:/Users/Kong/Pictures/Cap/Cap1.jpg"));
    String [] prefix={"C:/Users/Kong/Pictures/Cap/Cap1.jpg"};
    Random random= new Random();
    for (int i = 0; i < capth.length; ++i)
    {
    capth[i] = prefix[random.nextInt(10)] ;
    }
    p2.add(image);
    add(p2,BorderLayout.NORTH);
    }

    public static void main (String args[]){
    capt c=new capt();
    }
    }
    It seen like JLabel is not compatible with array.
    Can anyone help me to solve the problem?
    Last edited by JJay84; 04-06-2011 at 04:20 PM.

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    I don't know how to make it work
    What do you mean? Are there exceptions? Does it compile? I can say right now you've got an array of length 1 (prefix), and then try to access values from said array with indexes between 0 and 9...asking for an ArrayIndexOutOfBoundsException (and what you do with those arrays is not defined - an SSCCE would more clearly demonstrate the problem)

  3. #3
    JJay84 is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    It true, the program show an ArrayIndexOutOfBoundsException.
    Exception in
    capth[i] = prefix[random.nextInt(10)]
    &
    capt c=new capt();

    But I think the problem is,
    p2.add(image);
    I want to add the result of the random image inside the JLabel.
    It should be
    p2.add(capth[i]);
    However, it show that "cannot find symbol method add (java.lang.String)"
    Last edited by JJay84; 04-06-2011 at 04:35 PM.

Similar Threads

  1. Replies: 1
    Last Post: 03-20-2011, 12:06 AM
  2. Replies: 2
    Last Post: 11-24-2010, 03:38 PM
  3. Image On a JLabel
    By corbokhan in forum New To Java
    Replies: 11
    Last Post: 11-06-2010, 01:18 AM
  4. JLabel wont appear in front of background image
    By Andolph23 in forum AWT / Swing
    Replies: 5
    Last Post: 05-27-2010, 02:42 AM
  5. Image in JLabel
    By ishere11 in forum AWT / Swing
    Replies: 2
    Last Post: 04-29-2010, 09:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •