Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set location of JLabel in a JFrame with Java?
To set location of a component in a JFrame, use the setBounds() method. Let us first create a frame and a panel −
JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
frame.getContentPane();
Create a component i.e. label and set the dimensions using setBounds(). Here, you can set the location in the form of x and y coordinates −
JLabel label = new JLabel("Demo Label!");
Dimension size = label.getPreferredSize();
label.setBounds(150, 100, size.width, size.height);
The following is an example to set location of a label in a JFrame −
Example
package my;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
frame.getContentPane();
JLabel label = new JLabel("Demo Label!");
Dimension size = label.getPreferredSize();
label.setBounds(150, 100, size.width, size.height);
panel.setLayout(null);
panel.add(label);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(500, 300);
frame.setVisible(true);
}
}
Output

Advertisements
