Subclass AbstractBorder : Custom Border « Swing « Java Tutorial

Subclass AbstractBorder
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;

public class RedGreenBorder extends AbstractBorder {
  public boolean isBorderOpaque() {
    return true;

  public Insets getBorderInsets(Component c) {
    return new Insets(3, 3, 3, 3);

  public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    Insets insets = getBorderInsets(c);
    Color horizontalColor;
    if (c.isEnabled()) {
      boolean pressed = false;
      if (c instanceof AbstractButton) {
        ButtonModel model = ((AbstractButton) c).getModel();
        pressed = model.isPressed();
      if (pressed) {
        horizontalColor = Color.RED;
      } else {
        horizontalColor = Color.GREEN;
    } else {
      horizontalColor = Color.LIGHT_GRAY;

    g.fillRect(0, 0, width,;

  public static void main(String args[]) {
    JFrame frame = new JFrame("My Border");
    Border border = new RedGreenBorder();
    JButton helloButton = new JButton("Hello");
    JButton braveButton = new JButton("Brave New");
    JButton worldButton = new JButton("World");
    Container contentPane = frame.getContentPane();
    contentPane.add(helloButton, BorderLayout.NORTH);
    contentPane.add(braveButton, BorderLayout.CENTER);
    contentPane.add(worldButton, BorderLayout.SOUTH);
    frame.setSize(300, 100);

14.108.Custom Border
14.108.1.Creating Your Own Borders
14.108.2.implements Border interfaceimplements Border interface
14.108.3.Subclass AbstractBorderSubclass AbstractBorder
14.108.4.Creating a Compound Border
14.108.5.Creating and Setting a Raised BevelBorder from BorderFactory
14.108.6.Creating and Setting a Lowered BevelBorder from BorderFactory