How to add empty border to JPanel in Java?

Java 8Object Oriented ProgrammingProgramming

To add empty border, use the createEmtyBorder() method. Let us first create a new JLabel −

JLabel label;

label = new JLabel("Label with empty border!");

Now, set empty border using the setBorder() method −

label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

The following is an example to add empty border to JPanel −

Example

package my;
import javax.swing.BorderFactory;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("Label with empty border!");
      label.setFont(new Font("Verdana", Font.PLAIN, 16));
      label.setVerticalAlignment(JLabel.BOTTOM);
      label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      frame.add(label);
      frame.setSize(550,350);
      frame.setVisible(true);
   }
}

Output

raja
Published on 30-May-2019 11:47:55
Advertisements