I'm not sure what example you are working from, but here are a few things i would change. I have not made too many changes in the actual design of your class.
Primarily you need to declare the main method static:
public static void main(String[] args)
If this method is not static, you can't access it unless the class is instanciated. Since this method creates the Display class instance, its kind of a chicken and egg thing.
Secondly, as it looks now, you should create your Display object as a variable of the type Display. Then call the two methods in that object.
Display dis = new Display(); dis.createGUI(); dis.showUnit(0,0);
Since the createGUI method is empty, maybe you should remove it to make the code more clear.
In your showUnit method, you create a JFrame. If you think about it, you might see that the Display class already extends JFrame and thus is a JFrame. If you move the "JFrame name" from this call, to the call from main, you will still get a JFrame called "TopLevelDemo". To make this work, you will also need a constructor for the Display class.
public class Display extends JFrame { public Display(String string) { } public static void main(String[] args) { Display dis = new Display("TopLevelDemo"); dis.createGUI(); dis.showUnit(0,0); }
A final change to the code is the removal of a few things in the last three calls. You can add the JLabel directly to the Display JFrame. The same goes for pack and setVisible. Java "knows" that Display is a JFrame and will associate the calls with this JFrame.
private void showUnit(int x, int y) { ImageIcon unitImage = createImageIcon("images/middle.gif"); JLabel unitLabel = new JLabel(unitImage); unitLabel.setOpaque(true); unitLabel.setBackground(new Color(248, 213, 131)); unitLabel.setPreferredSize(new Dimension(16, 16)); unitLabel.setBounds(x, y, unitImage.getIconWidth(), unitImage.getIconHeight()); add(unitLabel); pack(); setVisible(true); }
To make things a bit clear (in particular with complex classes), I would add this to those 3 calls, to indicate that they are related to this object (the Display JFrame).
this.add(unitLabel); this.pack(); this.setVisible(true);
To reposition your JLabel, I suggest you use a LayoutManager. These are added to the (in this case) JFrame. Component are added differently that when drawing an image. If you were drawing the image directly to the JFrame, you could use the position as a parameter in the call.
g.drawImage(img, 100, 100, this);
Since you are using the image as a JLabel, you can devide the JFrame into different areas with a layoutmanager. To see the difference I have given your JFrame a size.
this.setPreferredSize(new Dimension(175, 100)); this.add(unitLabel, BorderLayout.NORTH);
Maybe you could give a description of what you expect the application to do, when you are surpriced the image is in the center of the frame.
[Edited by - MONDARIZ on December 30, 2008 5:23:18 AM]