Current Position:Home > Positioning JLabels

Positioning JLabels

Update:11-30Source: network consolidation
Advertisement
Hey,
I'm trying to learn Swing applications and I've run into a bit of trouble positioning my "Hello World" label on the screen. I've created a JFrame that is 640x480 in size and I want to move my label to a specific x,y within the frame. I've tried using setLocation and setBounds with no luck. The label stays stuck vertically centered on the left side of the screen. How do I move this label around?
Mike

The Best Answer

Advertisement
You need to read on the layout managers. For instance JFrame contentPanes use the BorderLayout as the default layout manager while JPanels use FlowLayout as the default managers. There are two ways to work here: 1) work with the the appropriate layout manager to place your JLabel in a position that will remain correct even if the JFrame is resized, or 2) set the contentPane's layout to null and place your JLabel by absolute positioning (i.e., setBounds or something similar). If you do the latter, you will have to set the size of the jlabel too (setBounds does this). I recommend the former technique over the latter.
For instance this adds a JLabel to a JFrame (via a JPanel) by the first method: the null layout with absolute positioning and sizing of the JLabel by calling its setBounds method:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class HelloWorldFrame
    // the JPanel that will hold our JLabel
    private JPanel mainPanel = new JPanel();
    public HelloWorldFrame()
        mainPanel.setPreferredSize(new Dimension(640, 480));
        mainPanel.setLayout(null); // use no layout manager
        JLabel helloWorldLabel = new JLabel("Hello World");
        // set the bounds: both the location x, y, and the size width, height
        helloWorldLabel.setBounds(20, 400, 100, 24);
        // so we can see the exact size of the JLabel
        helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
        mainPanel.add(helloWorldLabel); // add it to the JPanel
    public JPanel getMainPanel()
        return mainPanel;
    private static void createAndShowUI()
        // create a JFrame
        JFrame frame = new JFrame("HelloWorldFrame");
        // add our JPanel to this JFrame
        frame.getContentPane().add(new HelloWorldFrame().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    // call swing in a thread-safe manner
    public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
            public void run()
                createAndShowUI();
}And here I add the JLabel using the second technique: layout managers:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class HelloWorldFrame2
    // the JPanel that will hold our JLabel
    private JPanel mainPanel = new JPanel();
    public HelloWorldFrame2()
        mainPanel.setPreferredSize(new Dimension(640, 480));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 56, 0));
        JLabel helloWorldLabel = new JLabel("Hello World");
        // so we can see the exact size of the JLabel
        helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
        JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        labelPanel.add(helloWorldLabel);
        mainPanel.add(labelPanel, BorderLayout.SOUTH); // add it to the JPanel
    public JPanel getMainPanel()
        return mainPanel;
    private static void createAndShowUI()
        // create a JFrame
        JFrame frame = new JFrame("HelloWorldFrame2");
        // add our JPanel to this JFrame
        frame.getContentPane().add(new HelloWorldFrame2().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    // call swing in a thread-safe manner
    public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
            public void run()
                createAndShowUI();
}Edited by: Encephalopathic on Feb 18, 2008 7:58 PM
  • Positioning JLabels Update:11-30

    Hey, I'm trying to learn Swing applications and I've run into a bit of trouble positioning my "Hello World" label on the screen. I've created a JFrame that is 640x480 in size and I want to move my label to a specific x,y within the frame. I've t

  • Help with a simple GUI. Update:10-11

    I am totally new to building GUI's. Everything I have picked up I did so online. From what I have learned this should work, but it throws all sorts of exceptions when I run it. package com.shadowconcept.mcdougal; import javax.swing.*; import java.awt

  • How to align JLabels and set them to the rightmost position before the JTextField? Update:11-30

    I don't know if this is the right group to ask in. I am using the miglayout, and I want every JLabels to locate at the rightmost position next to the JTextField after it so that there won't be any gaps between the JLabels and the JTextFields Any exam

  • JLabel icon position question Update:11-30

    I want to have a JLabel with text and an icon. I want the text to be positioned on the left and I want the icon on the right. My question is: Is this possible and if so how?RTFM http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLabel.html#setHoriz

  • Illegal component position when add JLabel to JtextPane Update:11-30

    Hi all, I want to add a JLabel to a JTextPane, the label shoud be put in the lines of text just like the normal text. I have some questions: 1. How can I put the label in the position we want, when I use the method add(label, textPane.getStyledDocume

  • How to define the position of a JLabel in a JPanel? Update:10-11

    Could anybody help me for my problem ? - I added two JLabel into a JPanle using the folowwing code, but the two labels are displayed over each other. JLabel.setBounds() doesn't help. questionL1 = new JLabel("question1"); questionL1.setBounds(50,

  • Compilation error for JLabel - trying to position text & icon Update:11-30

    Hi, I'm still a Jnewbie & having difficulty understanding how this works. the error: C:\biz>javac -classpath C:\ Welcome.java Welcome.java:54: '.class' expected Member.setVerticalTextPosition(int BOTTOM ); ^ Welcome.java:54: ')' expected Member.set

  • Need help with animated JLabel Update:10-11

    I've created an animated extension of the JLabel which imitates a "typewriter" effect. It works smoothly for single-line labels. Here is a basic pseudo-code outline of how I went about doing it: constructor(String fullText, int delay) {   create

  • Why do I get Illegal Component position when I say FlowLayout.CENTER Update:10-11

    The code runs fine if you replace the line Jp7.add(submitButton, FlowLayout.CENTER); with Jp7.add(submitButton); I know FlowLayout's default location is CENTER. But when I explicitly say to center the button, it crashes during runtime but compiles fi

  • Adjust position and size of textField and button... Update:10-11

    Dear All, I have the following sample program which has a few textFields and a button, but the positions are not good. How do I make the textField to be at the right of label and not at the bottom of the label ? Also how to adjust the length of textF