Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set size for jLabel in swing

Tags:

java

swing

jlabel

I want to set a jLabel with dimension(50,75) inside a JFrame.

I tried using

label.setPreferredSize(new Dimension(50, 75)); 

But it doesnt work. How can I do this?

like image 957
ddk Avatar asked Nov 01 '22 13:11

ddk


1 Answers

setPreferredSize changes really the size of the label you should just try to draw it border using setBorder method to verify the new size, but the font size is not changed, if you want to have big font try to call setFont and set the new font size, here some code to start with:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

public class Test {
    public static void main(String[] args) {
        JFrame t = new JFrame();
        t.setBounds(100, 100, 500, 400);
        JLabel l = new JLabel("Hello");
        // new font size is 20
        l.setFont(new Font(l.getFont().getName(), l.getFont().getStyle(), 20));
        // draw label border to verify the new label size
        l.setBorder(new LineBorder(Color.BLACK));
        // change label size
        l.setPreferredSize(new Dimension(200, 200));
        t.getContentPane().setLayout(new FlowLayout());
        t.add(l);
        t.setVisible(true);
    }
}
like image 120
Naruto Biju Mode Avatar answered Nov 15 '22 05:11

Naruto Biju Mode