How to change JLabel size in Java?

Java 8Object Oriented ProgrammingProgramming

With Java Swing, you can set JLabel size as preferred size different than the default −

JLabel label.setPreferredSize(new Dimension(250, 100));

The following is an example to change JLabel size −

Example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.*;
import javax.swing.border.Border;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("This is demo label!",JLabel.RIGHT);
      label.setVerticalAlignment(JLabel.TOP);
      label.setFont(new Font("Verdana", Font.PLAIN, 15));
      label.setPreferredSize(new Dimension(250, 100));
      label.setForeground(new Color(120, 90, 40));
      label.setBackground(new Color(100, 20, 70));
      Border border = BorderFactory.createLineBorder(Color.ORANGE);
      label.setBorder(border);
      frame.add(label);
      frame.setSize(600,300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 09-May-2019 09:04:47
Advertisements