Search code examples
javaswinglocationjlabeljcomponent

Java JTextArea, JLabel, and other Components: How to set Location


If I have a JLabel, for example, and I call the setLocation() method, nothing happens. Same with all the other JComponents. How can I specify the location? It would be nice to be able to move these Components wherever I want to.


Solution

  • I'm guessing that the LayoutManager of your panel or frame is setting the location of the label for you.

    What you need to do is set the layout to null (this will make it so the frame doesn't try to layout the components by itself):

    public GUI() 
    {
        setLayout(null);
    } 
    

    I don't condone this workaround however, since LayoutManagers are extremely useful in mapping out where components should go. Also, when the LayoutManager is null, you'll have to keep track of new components each time, perform layout computation yourself when the window moves shrink, etc. Take a look at this tutorial for help with LayoutManagers