import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JLabel; class ShowPicture { public static void main(String args[]) { var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon); frame.add(label); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }You can create an instance of the Purchase class with the line
var purchase1 = new Purchase();So in the code, you can do the same kind of thing. You can create instances of the JFrame, ImageIcon, and JLabel classes with the following lines:
var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon);Here’s some gossip about each of these lines:
-
A JFrame is like a window (except that it’s called a JFrame, not a “window”). The line
var frame = new JFrame();
creates a JFrame object, but this line doesn’t display the JFrame object anywhere. (The displaying comes later in the code.)
-
An ImageIcon object is a picture. At the root of the program's project directory, there is a file named androidBook.jpg. That file contains the picture. The line
var icon = new ImageIcon("androidBook.jpg");
creates an ImageIcon object — an icon containing the androidBook.jpg picture.
You can use almost any .gif, .jpg, or .png file in place of the (lovely) Android book cover image. To do so, drag your own image file to Eclipse's Package Explorer. (Drag it to the root of this example's project folder.) Then, in Eclipse's editor, change the name androidBook.jpg to your own image file's name. That's it!
-
You need a place to put the icon. You can put it on something called a JLabel. The line
var label = new JLabel(icon);
creates a JLabel object and puts the androidBook.jpg icon on the new label’s face.
Well of course, you put it on a JLabel.” When you’ve worked long and hard with Java’s Swing components, all these things become natural to you. But until then, you look everything up in Java's API documentation.
You never need to memorize the names or features of Java’s API classes. Instead, you keep Java’s API documentation handy. When you need to know about a class, you look it up in the documentation. If you need a certain class often enough, you’ll remember its features. For classes that you don’t use often, you always have the docs.