How can we apply different borders to JButton in Java?


A JButton is a subclass of AbstractButton class and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate MouseListener when a user can do some actions from the mouse and KeyListener when a user can do some actions from the keyboard.

We can set different borders like LineBorder, BevelBorder, EtchcedBorder, EmptyBorder, TitledBorder, etc to JButton using the setBorder() method of JComponent class.

Syntax

public void setBorder(Border border)

Example

import javax.swing.*;
import java.awt.*;

public class JButtonBordersTest extends JFrame {
   private JButton button[];
   private JPanel panel;
   public JButtonBordersTest() {
      setTitle("JButton Borders");
      panel = new JPanel();
      panel.setLayout(new GridLayout(7, 1));
      button = new JButton[7];
      for(int count = 0; count < button.length; count++) {
         button[count] = new JButton("Button "+(count+1));
         panel.add(button[count]);
      }
      button[0].setBorder(BorderFactory.createLineBorder(Color.blue));
      button[1].setBorder(BorderFactory.createBevelBorder(0));
      button[2].setBorder(BorderFactory.createBevelBorder(1, Color.red, Color.blue));
      button[3].setBorder(BorderFactory.createBevelBorder(1, Color.green, Color.orange, Color.red, Color.blue));
      button[4].setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      button[5].setBorder(BorderFactory.createEtchedBorder(0));
      button[6].setBorder(BorderFactory.createTitledBorder("Titled Border"));

      add(panel, BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonBordersTest();
   }
}

Output

raja
Published on 10-Sep-2019 14:58:38
Advertisements