Chandrasekhar Malladi
Chandrasekhar Malladi

Reputation: 351

Positioning a label using swing in java

I have been using jFrame to build a GUI. I had to insert images in the GUI, for which i inserted a label and put the image as an icon for the label. Now, i have to find out the position of the image in terms of the x and y co-ordinates and i am unable to do that. I have used

 setLocaction(x,y);

but it still doesn't seem to work. I even disabled the layout manager by using

 setLayout(null); 

What is the possible solution for this problem?


Edit

Basically i am creating a Solar system GUI using Swing, so the positions of the planets are to be set by me. I being new to java, there is being some difficulty in implementing the layouts.

Upvotes: 0

Views: 175

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

This isn't a layout issue at all, but a drawing and possibly an animation issue. If this were my project, I'd

  • First and foremost, separate out the program logic from its display, a la the MVC or Model-View-Control pattern, or one of its many variants.
  • Create one JPanel for the GUI's graphics and do all my drawing in this
  • I would not display my planet images using ImageIcons inside of JLabels.
  • Rather, I'd create a background image and draw my planet sprites inside of the drawing JPanel's paintComponent method.
  • I'd create non-GUI Planet classes that a non-GUI model would hold.
  • In the GUI portion of my program, I would associate a BufferedImage with each Planet, probably using a HashMap<Plant, Image>.
  • I'd then draw each Planet's associated image in the drawing JPanel's paintComponent(...) method, and place it depending on the Planet's position field values.
  • If I wanted to animate this, I'd use a Swing Timer to drive my simple animation.

Upvotes: 2

Naruto Biju Mode
Naruto Biju Mode

Reputation: 2091

With null layout you should use setSize and setLocation methods on you label to get your image visible correctly inside your frame.

Upvotes: -1

Related Questions