WantTobeAbstract
WantTobeAbstract

Reputation: 133

How to change the position of label in frame using java

I have just started with making frames in java and wrote the following code :

 import javax.swing.*;

public class HelloWorldFrame extends JFrame

{       
  public static void main(String[] args)
{   
  new HelloWorldFrame(); 
}
HelloWorldFrame()
 {
    JLabel jlb=new JLabel("HelloWorld");  
    add(jlb);
    this.setSize(100,100);
    setVisible(true);
 }
}   

Can anyone help explaining how can I change the position of label in the above code

Upvotes: 1

Views: 18602

Answers (2)

Kevin Avignon
Kevin Avignon

Reputation: 2903

It is fairly easy to change the position of your JLabel instance by using two methods which are really handing. Look below for the code to use :

HelloWorldFrame()
 {
    JLabel jlb=new JLabel("HelloWorld");  
    jlb.setHorizontalAlignment(50); // set the horizontal alignement on the x axis !
    jlb.setVerticalAlignment(50); // set the verticalalignement on the y axis !
    add(jlb);
    this.setSize(100,100);
    setVisible(true);
 }

You can learn more about JLabel and how to manipulate them here : http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html

//EDITS

Base on the comment that I've given earlier, the alignement that was given could not work. So I made the necessary changes to make them work !

 HelloWorldFrame()
     {
        JLabel jlb=new JLabel("HelloWorld");  
        jlb.setHorizontalAlignment(SwingConstants.CENTER); // set the horizontal alignement on the x axis !
        jlb.setVerticalAlignment(SwingConstants.CENTER); // set the verticalalignement on the y axis !
        add(jlb);
        this.setSize(100,100);
        setVisible(true);
     }

Upvotes: 2

npinti
npinti

Reputation: 52185

Usually (read recommended) what you are after is achieved through the use of Layout Managers. If that does not work for you, you would need to use setLocation(int x, int y) and combine it with this.setLayoutManager(null) (or something like that). This will remove the default layout manager and give you complete control on where/how are your object placed.

EDIT: As outlined by @AndrewThompson, please go for the first approach rather than the second unless you really, really have to.

Upvotes: 2

Related Questions