Using a vector / array/ arraylist. .   something!  . . . to return an image

I'm trying to create a class with a method that randomly returns one of five images. I can't figure out how to do it. Everything I try goes wrong because I can't figure out what kind of object to create in the method. My latest attempt (below) was with ArrayList, but the compiler keeps telling me:
smallPix2.java:32: array required, but java.util.ArrayList found
     return icons[num];
Here's the code. Any feedback appreciated:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Random;
public class smallPix2 extends JFrame {
     ImageIcon img1 = new ImageIcon("Art//boutet.jpg");
     ImageIcon img2 = new ImageIcon("Art//curlu.jpg");
     ImageIcon img3 = new ImageIcon("Art//helleu.jpg");
     ImageIcon img4 = new ImageIcon("Art//ranson.jpg");
     ImageIcon img5 = new ImageIcon("Art//zamora.jpg");
ImageIcon picks() {
     ArrayList icons = new ArrayList();
     icons.add(img1);
     icons.add(img2);
     icons.add(img3);
     icons.add(img4);
     icons.add(img5);
     Random rando = new Random();
     int num = rando.nextInt(5);
     return icons[num];
}

you have defined icons to be an ArrayList. So to reterieve data from it you should use its get() method.
icons.get(num);if you look at the ArrayList API, this will return a type Object. You obviosly want to return an ImageIcon, and seeings you know that they are ImageIcons in there you can cast the object to ImageIcon:
return (ImageIcon)icons.get(num);

Similar Messages

  • Using conversion to array to add 16 bit grayscale images

    Dear all,
    Usual disclaimers, first post, tried to search using a variety of terms, no luck, so posting a new question!
    I am trying to perform a running a verage of a 16 bit grayscale image. I do not have access to the Vision development module.  My 'workaround' is to grab the image, convert to array and then, using a shift register, to add this array to that acquired at the previous loop iteration. The problem I am having is that the shift register, despite being fed data in a 16 bit unsigned word formatt, returns 8 bit data. The add function is then trying to add 16 bit to 8 bit data and returns an empty array.
    Can anyone help? Surely it must be possible to use shift registers with arrays of 16 bit data?
    Any help appreciated!

    Shift registers work with all datatypes. Can you show us your code?
    LabVIEW Champion . Do more with less code and in less time .

  • Vector or ArrayList  use for dropdown with more than 1000 entries

    Hi Friends
    I am having more than 1000 entries of different TimeZone's which i need to display in a dropdown list.
    i am not able to decide whether i need to use a Vector or Arraylist for storing these values.
    please let me know which one will be best suited to use in case the list entry is more than 1000 characters.
    waiting for a positive reply from your side.
    Thanks & Regards
    Vikeng

    A JComboBox can be constructed from a Vector (rather than any other sort of List) without having to implement your own ComboBoxModel. (JList is similar).
    I agree with kajbj - a control like this with a thousand entries is rather poor interface design. One exception might be if the entries are sorted in some way, and you "jump" to the appropriate place in the list as the user types.

  • Use of Vector in undo operation ?

    Hello,
    I am developing simple paint program. And want to use undo redo operation for drawing in drawing canvas. Actually I have done it with the help of Vector. But the problem is that it is not working properly. The first drawn shape is not removing with this operation and also the problem is that When i am using CTRL+Z for undoing last drawing. It is not removing last drawn shape with first undo operation. Let me know that what is the exact problem in my coding. I am not fully java programmer. So please tell me what to do for that. I want to draw n level of drawing on drawing canvas and also want to perform n level (first drawn shape) undo actions. And also want to know how to make redo button for same coding only use of Vector or ArrayList.
    My code is here:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import java.util.*;
    public class PaintUndo extends JFrame
         Display pan = new Display();
    public PaintUndo()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         getContentPane().add("Center",pan);
           setBounds(1,1,600,400);
         JMenuBar  menu = new JMenuBar();;
         JMenu     submenu;
         JMenuItem item, redo;
         submenu = new JMenu("Edit");     
         item = new JMenuItem("UnDo");
        item.setMnemonic(KeyEvent.VK_Z);
            item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
         item.addActionListener((ActionListener)pan);
         submenu.add(item);   
         menu.add(submenu);
         getContentPane().add("North",menu);
         setVisible(true);
    public class Display extends JComponent implements MouseMotionListener, MouseListener, ActionListener
         Vector   saves = new Vector();
         BufferedImage image = null;
         Graphics ig;
         Graphics pg;
         Point point;
        int x1=0;
        int y1=0;
    public Display()
         setBackground(Color.pink);
         addMouseMotionListener(this);
        addMouseListener(this);
    public void paintComponent(Graphics g)
         if (image == null)
              image = (BufferedImage) createImage(800,600);
              ig = image.createGraphics();
              ig.setColor(Color.white);
              ig.fillRect(0,0,800,600);
              ig.setColor(Color.blue);
              pg = getGraphics();
              pg.setColor(Color.blue);
         g.drawImage(image,0,0,this);
    public void mouseDragged(MouseEvent e)
            int x2 = e.getX(); int y2 = e.getY();
                Graphics gr = image.getGraphics();
                   gr.drawLine(x1, y1, x2, y2);
                repaint();
                x1 = x2; y1 = y2;
    public void mouseMoved(MouseEvent e)
    public void actionPerformed(ActionEvent a)
         if (a.getActionCommand().equals("UnDo") && saves.size() > 0)
              ig.drawImage((Image)saves.remove(saves.size()-1),0,0,null);
              repaint();
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked....");
            public void mousePressed(MouseEvent e) {
                System.out.println("mouse pressed....");
                x1 = e.getX();
                   y1 = e.getY();
            public void mouseReleased(MouseEvent e) {
                System.out.println("mouse released....");
               Image tmg = createImage(800,600);
              Graphics tg = tmg.getGraphics();
              tg.drawImage(image,0,0,null);
              saves.add(tmg);
            public void mouseEntered(MouseEvent e) {
            public void mouseExited(MouseEvent e) {
    public static void main (String[] args)
         new PaintUndo();
    }This is complete code for undoing.
    Any help will be appreciated.
    Thanks in advance.
    Manveer

    The example code is set up for a protocol completely different than what you are doing, so you can't simply copy it and hope it works.  The example code expects that the other side will send a 4-byte header containing the number of data bytes that follow, then send the data.  The example code first reads that 4-byte header, casts it to an integer, and reads that number of bytes (the second Bluetooth Read).
    When you run this with your device, the first read gets your 4 bytes - FF FF 22 33 - and converts that to an integer.  0xFFFF2233 is decimal 4294910515.  So you then try to read this huge number of bytes and you get an error - looks like error 1, an input parameter is invalid, because you can't read 4GB at once.  You can probably get your code working with a single Bluetooth Read, with a 1 second timeout (because you have a 1 second delay between packets).  You'll want to wire in some number of bytes to read that is at least the size of the largest packet you ever expect, but don't use a ridiculously huge number that generates an error.  LabVIEW will return as many bytes as are available when the timeout expires, even if it isn't as many as you asked to read (you might also get a timeout error, though, which you'll need to clear).  You can then do whatever you need to do with that data - search for FF FF, typecast anything after that to array of U16, display it. 
    The output of the Bluetooth Read is a string, but it's not text - it's exactly the bytes that were sent.  The Y with the dots over it is the way ASCII 255 (0xFF) displays (at least in that font).  ASCII 34 (0x22) is ", and ASCII 51 (0x33) is the number 3.

  • Justification for using HashMap and not ArrayList

    Hi, I've recently completed a project for my course and now I'm doing the write up for it. Part of my project was to load a dictionary into a data structure. I went with a HashMap because I had code from a previous project to help implement it, the dictionary was used to check possible decrypted words and return possible words that the half decrypted word could be.
    Now I should justify my use of HashMap v ArrayList. Time complexity of ArrayList is better than the hashmap if im correct, so are there any 'technical' reasons I could say why I chose the HashMap:
    ArrayList O(1)
    HashMap O(n)
    So searching 50,000 + words would be best using an arraylist? Could anyone possibly give a good reason why hashmaps would be better than arraylists?

    Linear searching is (generally) the slowest way to find something.
    If you know the exact location of what you're looking for, then obviously just accessing it using an ArrayList would be fast. Using a HashMap you can, by using the input key, figure the index of the bucket which contains your data, so you don't have to linearly search through the whole map just to find what you're looking for, your key gives you it's location.
    I'm sure these links can explain stuff better than I did:
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html

  • Use of Generics in ArrayList now mandatory?

    Hi,
    I'm writing a little Applet involving the population of ArrayList (my Java compiler is version 1.6.0_22).
    My code is similar to
    ArrayList vertexPoints = new ArrayList();
    - it compiles OK, but when I try and run the applet, it falls out saying that there is a NullPointerException in the above line. I was under the impression that the use of generics in ArrayLists is not compulsory? Or will I have to
    change the code to something like
    ArrayList<3DPoint> vertexPoints = new ArrayList<3DPoint>():
    Some websites with tutorials give the impression that providing a type is optional, hence my confusion.

    799615 wrote:
    but accessing a method of an array of objects. I'll soldier on....Since you have not provided any more information we can only make educated guesses. Perhaps you are doing something like:
    Foo[] fooList = new Foo[5];
    fooList[0].doStuff(); // NullPointerExceptionWhy? The first line only creates an array. It does not automagically create any Foo objects for you. Therefore the array is full of the deafult value and for Objects (reference types) it is null. So effectively the second line is null.doStuff().

  • Using a vector in Java IDL...URGENT!

    How can I use a vector in Java IDL? I am trying to have a function return a vector.
    From what I have read, I should use a sequence. Therefore I tried the following code:
         struct ItemDB {
              long ItemNumber;
              long Quantity;
              double Price;
    typedef sequence <ItemDB> ItemList;
         interface ProductOperations{          
              ItemList listItems();
    When the equivalent Java is generated for the interface I am forced to return an array instead. This is what is generated:
    public interface ProductOperationsOperations
    ItemDB[] listProducts ();
    However, this is an array, which is bounded. I want to use an unbounded storage device.
    Can someone please please assist me. I appreciate it.
    Thanks
    RG

    This is already an unbounded sequence
    typedef sequence <ItemDB> ItemList;
    Checkout the read/write methods in the Helper class and you can see that the above list is unbounded.

  • Help with a Vector Array - pppppplllllllleeeeaaasse!!!!!!!

    Hi I'm having a mare with a Vector Array that I want to contain String variables. I know you get a warning with the traditional implementation of a vector, and I have over come that using:
    private Vector <String> MyVector = new Vector<String>();
    But I also need to create a Vector Array and I am getting some very strange results - for a start in JPadPro it only comiles every second attempt, with every other failing due to the implementation of the Vector array.
    Below is a snippet of the code that I have sort of got to compile but with a compiler warning:
    private Vector<String>[] MyVector; //this is line 75
    int Array;
    public myClass()
    Array = 5;
    MyVector = new Vector[ Array ];
    for( int i = 0; i < Array; i++ )
    MyVector[ i ] = new Vector<String>();     
    The first time I complie I get:
    CreateMessage.java Line 75: Syntax Error
    The Second time I compile I get:
    CreateMessage.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Finished
    I hate complier errors - I have gotten quite a few but have managed to remove them all but this one by searching the forum. Any help on the correct implementation of my Vector Array would be great,
    Thanks in advance,
    Kris

    Mr_Bump180 wrote:
    Well you lot are a real cheery bunchDo you come here for warm and fuzzies or for Java help?
    - please accept my most humble apologies for daring to try and keep my thread light hearted. Use your brain. Nobody objects to keeping your thread lighthearted. It's that garbage like that is annoying and makes your post harder to read. If you want to get your question answered clear communication is of the essence. That should be common sense.
    I asked the question simply as I wanted to improve my code - which I write for no gain, but just in an attempt to automate processes that I cannot find software to do for me. How is that relevant?
    I find the solutions on this website invaluable, but what shines through most clearly - is the incredibly poor attitude of some of you - who are obviously java professionals - when a novice risks posting a question on what is obviously YOUR forum. Is that how you get your kicks? By jumping all over people that dare to ask a question in order to try and better themselves?Right. People jumped on your for asking a question. Get real.
    I will as I always do, read the pages you have linked to, and I will also try and implement your solution into my code - I just find it a shame that in order to obtain any help people who are posting in the "New to Java Programming" by-the-way, run the gauntlet of your abuse if the question, grammar, syntax or perhaps even title don't measure up to your high standards.Dude, if you're asking somebody to volunteer his time to help you, isn't it obvious that it's in your best interest to make it as easy as possible for him to do so?
    I will now turn the watch off this thread, and will not reply againAs if anybody cares.
    - but for those of you reading - I wonder just how many can't bare me to have the last word and have to post a replySo, anytime somebody replies to something it must be because they have to have the last word?
    with the clever little quote inserts, a greater than thou attitude, and some more brilliant humour (I was in stiches reading your rebuttals ) because I don't fully understand a concept and as such asked for help.Get over the "they teased me because I don't know Java" bullshit. It's simply not the case, and you bloody well know it.

  • Using enums or Arrays?

    Hi all,
    I have a bunch of constants for one particular object. I also have a bunch of constants for another object. Each constant in one object has its equivalent in the other object, for example constant A in object 1 is equivalent to constant B in object 2. I want to create a hashMap having the constants from one object being the keys, with the equivalent constant in the other object being the values. I was just wondering should I use enums to store the constants and use the .values() method to loop through , or use a string array, or use an ArrayList? What are the advantages pitfalls for both? Which is better programming practice!
    Thanks and regards!

    It sounds to me like making a separate representation of just the names of the elements would be overkill. I mean, you could, but it's not clear to me what the advantage would be. It might be easier just to put the data type representation in the javadocs, or if you really want to be explicit you could have an interface for the objects that do the parsing, and specify a method like:
    public String getDataTypeName();And then provide implementations like:
    public String getDataTypeName() { return "R4"; }I mean, do you really need to look these things up by name?
    Edited by: paulcw on Feb 9, 2010 10:49 AM

  • How to create spark skins using fxg vector graphics&how to switch b/w spark skins at runtime/via XML

    Hi,
    I want to create a number of Spark Skins using some vector images that I have with me. I can obtain the vector images in FXG format-- but what I am looking for is some way to quickly create multiple skins for various UI elements like buttons, menus, radio button, checkboxes, etc -- not by converting the fxg->mxml but by using fxg files directly (after including them in the skins project in Flash Builder 4.6). Since I want to create many such skins (atleast 8-10) what is the fastest way of accomplishing this?
    Also, once I create multiple Spark Skins, how do I switch from one skin to another, in a running app? -- something like a template switcher, where the user viewing the flex app chooses a color, and the spark skin is immediately changed to the skin of that color (I would have already created the skin...). And can I store this skin template value in an XML? So that the end user can simply change this param in XML to change the design of the flex app?
    Arvind.

    Follow-up:
    Out of pure wishful thinking I decided I would just see what happened if I pretended 'exportFXG' was already a part of JSFL. Based on the signature of 'exportPNG', i tried the following lines:
      var success = fl.getDocumentDOM().exportFXG("file:///C:/mySymbol.fxg"); 
      fl.trace("success:"+success); // output: success:true 
    It worked! Fantastic! I'm not sure if exportFXG is considered still in "beta" and therefore intentionally excluded from the docs, or if it was just an oversight. But at least it gives us something to experiment with.

  • Using a vector graphic for a button

    Adobe Photoshop, Illustrator, and Encore CS5, everything is patched, Windows 7 64-bit
    I have been reading various posts, and either not seeing or not understanding something about using a vector graphic as a button on a menu.
    I drew a one-color shape in Illustrator, saved it as EPS and PNG and used it in a menu designed in Photoshop. When I preview it in Encore or burn a DVD, the graphic looks awful. And I'd like to use highlighting with it so it changes color when selected but that is another problem....
    To start the menu, I used the Photoshop preset NTSC DV Widescreen which has a pixel aspect ratio of 1.21. Then I added background graphics and so on. Each button is contained in a layer group named (+)PlayAll, etc. In each layer group is a text layer that doesn't have a prefix (e.g., Play All) and another layer with the vector or PNG named (=1)kv, which is the name of the EPS or PNG file.
    The behavior is fine. The graphic moves to indicate which menu item is selected, the text is constant, never changes.
    In Photoshop, the graphic looks fine but when I preview it in Encore it looks crappy and pixelated. What do I do?

    Part of the problem is I have no idea what some of these terms mean ... "2-bit indexed", ... The first one might mean an object that has one color,
    It is not the same as one color, and yes, it probably means more than any of us intend.  See  Encore help regarding button subpictures, in particular the part regarding using Photoshop to create button subpictures.
    The latter includes "(Technically, the subpicture overlay is a two‑bit indexed image.)," but you don't need to understand the technical meaning (they don't explain it anyway).  You do need to understand the liimitations they explain there,  For example, under "solid colors only," they say "Elements on these layers must use solid colors and sharp edges. Use one solid color per layer. Do not use gradients, feathering, or anti-aliasing on the subpicture layers. Color gradations are not possible in subpictures."
    "sub-picture highlight" ... the second one is probably made up.
    Heh, heh.  Searching that in Encore help (which I often find lacking) finds the page on Button Subpictures.  I agree that some of the terms, whether they are from the DVD specs or Sonic's applications (on which Encore is based), can make it difficult to look things up.
    "vector layer".... I searched Photoshop help for "vector layer" and got nothing. There is such a thing as a vector mask on a layer but I have no clue what a vector layer is.
    You're correct - vector mask.  Within a button group, the vector mask will be part of a layer, so I think of it as the button group "vector mask" layer.  That's part of why I pointed to using a library menu and editing in photoshop so you could compare what you have to what a template looks like.
    Please suggest which Encore library menu I can try. I opened a couple and couldn't figure out how they worked.
    In the General set, pick the Sunset menu.  Edit in Photoshop.  Expand the "(+) play movie" layer.  The "button vector mask" (the dark area) is in the layer called "button."  Notice that it does not have a (=1) or other indicator that it is a highlight.  In other words, it will just sit there, in whatever color is defined, and will not be a highlight.  If you put it in a layer that has one of the highlight indicators (the =1, =2 etc), it will then be subject to the subpicture highlight limitations.
    You might try your graphic in such a non-subpicture layer, and compare its appearance to putting it in a subpicture layer.
    Jeff Bellune's book (he's a moderator here) is still very applicable.  While some things have change, the basics haven't.
    But, hey, Jeff.  Why haven't you updated your book yet?  Inquiring minds want to know!

  • Re-using the same array on the same page later

    i am using an array to write values to a text file, is there a way to re-use that same array on the same page... after the values has been writen to a file, clear the values and use it again(no need to re-size it), just use it again....

    Thanks. I have a text box that takes a project id and calls a method that gets the data from db and stores it in a vector than i am looping throught the vector and assiging the values to an array and writing each value to a text file. i want to add another text field on there and see if the user wants to pass another project id (passing two) so i have to re-use the arrays again if the text box is not null. don't i need to re-define the arrays again to use them?

  • Can someone tell me how I can use a Vector to access my class?

    I wrote a class that will need to be instantiated with unknown instances later. I decided to use a Vector to do this. However when I created the vector:
    <CODE>
    Vector user = new Vector(1,1);
    user.addElement(Users());
    user.elementAt(0).name="Test";
    </CODE>
    I'm really not sure how I can set this. The class is of course Users and I want to set user as the Vector but specify Users as the Object Type. Any help? By the way I heard Java has a dynamic array feature is this true? I heard you had to use Vectors for Java. Also how can I free up the memory when I'm done with the class?

    Suppose class User looks like this:
    public class User
      public String name;
    }then you could do:Vector users = new Vector(1,1);
    users.addElement(new User());
    ((User)users.elementAt(0)).name="Test";BTW - Java is NOT C++, you always need to use the new keyword for object creation!

  • I purchased lightroom 4 Student Teacher Edition. I am not a student. Will I be able to use it or do I need to return to Best Buy?

    I am trying to find out if I am able to use lightroom 4 Student Teacher Edition. When I purchased it I was not aware of this. I am not a student.
    Will I be able to install and use it, or do I need to return to Best Buy and get something else.
    Please help.
    Thank you,

    > CS6 will only be available for purchase until May 30th and then Creative Cloud takes over completely.
    That is not correct. We are still selling CS6 software for quite some time. Where did you see an indication otherwise?
    Regarding Dynamic Link: In the current versions of the applications, no suite is required. For example, if you have the single-application subscriptions for both Premiere Pro CC and After Effects CC, Dynamic Link works between them. Dynamic Link is still limited to working between applications that share the same major version (i.e., CS6 with CS6, CC with CC, and so on).

  • Vector vs ArrayList

    Is it better to use a Vector or an ArrayList to store objects?? and why?

    If you have multiple Threads and they access the same ArrayList, you can run into concurrency problems because the structure is not synchronized. Vector doesn't have this problem, all of its methods are sync. Using the ArrayList external sync call will make it about as slow as a Vector, if not slower.
    http://java.sun.com/docs/books/cp/
    The book on concurrent programming.
    http://g.oswego.edu
    The site on concurrent programming.. util.concurrent

Maybe you are looking for

  • Problem Creating Partner Link for Adapter Integrating with Tuxedo using JCA

    Hi All, This is the first time that I am working on integration tools. I will explain in brief the problem. There will be a legacy system (Tuxedo) running which connect to legacy database for requests. I am able to connect to that legacy system using

  • Getting jeditorpane to scroll to a piece of text

    I am highlighting text in a JEditorPane and can't figure out how to get the pane to scroll so the hightlighted text is visible. Any ideas? Thanks

  • MBAM 2.5 SSRS SSL Error

    Greetings, I am in the process of building MBAM 2.5 and have encountered a critical stopping point when setting up the Reports feature for SSRS.  The following specifics relate to my infrastructure: - MBAM 2.5 Standalone on Windows 2012 R2 Standard -

  • Need guidence to store scan pdf in oracle 10g

    Hello guru I have 20000000 (2 corer) A4 size scan pdf containing text and images having Average size 0f 0.5 mb. please guide me how can i store it in oracle database and what i have to do for same. I am using oracle 10g forms as a front end for inser

  • What happened to my "Format" Pull-Down RoboHelp menu?

    I am using RoboHelp 8. The normal "Format" menu view disappeared -- and now the only choice available is "Apply Conditional Build Tag." Does anyone know how to restore the menu to the normal view? Thank you in advance...