I am learning Java and I have noticed when setting an image to an icon they use: Icon img1 = new ImageIcon(getClass().getResource("YES.png"));
getClass() method followed by a dot and another method next to it? If they were arguments to the ImageIcon constructor, shouldn't they be separated by commas? What does this mean?
In another topic, setLayout(new FlowLayout()); for example, uses the new operator inside a method without the object reference variable such as button = new button(); Why are they only using the new keyword without the object reference? How is this possible? Thank you all in advance for the responses, they are very appreciated.
I am assuming you already know what the dot notation means when used with an object reference and are just confused about using it with method call. If not do as nuzzle has suggested and read a basic tutorial.
Basically what you have shown a just a shorthand way of writing code. Rather than assign the reference returned from getClass() to a local variable and then using that local variable to call the object getResource(..) method you can write in as you have shown. In fact you can chain as many method calls as you like provide each method call returns an appropriate object reference for the following call. Back to your example, the following code snippets are essentially the same:
Icon img1 = new ImageIcon(getClass().getResource("YES.png"));
Class c = getClass();
URL url = c.getResource("YES.png");
Icon img1 = new ImageIcon(url);
The second example you have shown is also a form of shorthand similar to the example above - I'll leave you to work that one out.
Thank you. So instead of using the reference returned by the method; the method itself is called, I understand now, the other question about the new operator still hangs for me. Your response is appreciated double since you actually answered it and not told me to basically "Google it" as the post above.
Last edited by Fanatic2012; November 22nd, 2012 at 02:37 PM.
the other question about the new operator still hangs for me.
It's exactly the same thing, the setLayout(..) method calls requires you pass a reference to a LayoutManager. new FlowLayout() creates an instance of FlowLayout and returns a reference to the created object. Now work the rest out yourself - it's exactly the same as the other issue you had.