How can we set the margin to a JButton in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonMarginTest extends JFrame {
   private JButton button;
   public JButtonMarginTest() {
      setTitle("JButtonMargin Test");
      setLayout(new BorderLayout());
      button = new JButton("JButton Margin");
      button.setMargin(new Insets(50, 50, 50, 50));
      add(button, BorderLayout.NORTH);
      setSize(400, 400);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonMarginTest();
   }
}

Output

raja
Published on 24-Jul-2019 18:49:38
Advertisements