How to add empty border to a JButton in Java?

Java 8Object Oriented ProgrammingProgramming

To add empty border to a component, use the BorderFactory class createEmptyBorder() method −

Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 0, 0);

To set the above border to a component, use the setBorder() method −

JButton button = new JButton("Empty Border");
button.setBorder(emptyBorder);

The following is an example to ad empty border to a JButton −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.SoftBevelBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Border raisedBorder = new SoftBevelBorder(SoftBevelBorder.RAISED, Color.GREEN, Color.GREEN.darker(),
      Color.MAGENTA, Color.magenta.brighter());
      Border raisedBorder2 = new SoftBevelBorder(SoftBevelBorder.RAISED);
      Border loweredBorder = new SoftBevelBorder(SoftBevelBorder.LOWERED, Color.ORANGE, Color.YELLOW.darker(),
      Color.BLUE, Color.yellow.brighter());
      Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 0, 0);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton loweredButton = new JButton("Lowered Border");
      loweredButton.setBorder(loweredBorder);
      JLabel raisedLabel = new JLabel("Raised Border");
      raisedLabel.setBorder(raisedBorder2);
      JButton button = new JButton("Empty Border");
      button.setBorder(emptyBorder);
      Container contentPane = frame.getContentPane();
      contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(loweredButton,BorderLayout.EAST);
      contentPane.add(raisedLabel,BorderLayout.CENTER);
      contentPane.add(button,BorderLayout.NORTH);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 31-May-2019 10:55:53
Advertisements