implements Border interface : Custom Border « Swing « Java Tutorial






implements Border interface
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;

class SimpleBorder implements Border {  
  int top;  
  int left;   
  int bottom;   
  int right;  
  Color color = null;   

  public SimpleBorder() {  
      this.top = 2;   
      this.left = 4;   
      this.bottom = 8;   
      this.right = 10;   
      this.color = Color.RED;   
  }   

  public void paintBorder(Component c, 
                          Graphics g,  
                          int x, int y,
                          int width, int height) {


      Insets insets = getBorderInsets(c);   
      if (color != null)  
          g.setColor(color);  


      g.fill3DRect(0, 
                   0, 
                   width-insets.right, 
                   insets.top, 
                   true); 

      g.fill3DRect(0, insets.top, insets.left,  
                      height-insets.top, true);   
      g.fill3DRect(insets.left, height-insets.bottom,   
                   width-insets.left, insets.bottom, true);   
      g.fill3DRect(width-insets.right, 0, insets.right,   
                   height-insets.bottom, true);   
  }   

  public Insets getBorderInsets(Component c) {  
      return new Insets(top, left, bottom, right);  
  }   

  public boolean isBorderOpaque() {   
      return true;  
  }   
}

public class CustomBorderDemo {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("Aaaaaaaaaaa");
    button.setBorder(new SimpleBorder());
    frame.add(button);
    frame.pack();
    frame.setVisible(true);
  }

 
}








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