Create custom Bottom Border in Java

Description

The following code shows how to create custom Bottom Border.

Example


//w w  w. ja va 2  s. co m
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.AbstractBorder;
public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Sample Borders");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel aLabel = new JLabel("java2s.com");
    aLabel.setBorder(new BottomBorder(Color.RED));
    aLabel.setHorizontalAlignment(JLabel.CENTER);

    frame.add(aLabel);
    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}

class BottomBorder extends AbstractBorder {
 protected int thickness;

 protected Color lineColor;

 protected int gap;

 public BottomBorder(Color color) {
   this(color, 1, 1);
 }

 public BottomBorder(Color color, int thickness) {
   this(color, thickness, thickness);
 }

 public BottomBorder(Color color, int thickness, int gap) {
   lineColor = color;
   this.thickness = thickness;
   this.gap = gap;
 }

 public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
   Color oldColor = g.getColor();
   int i;

   g.setColor(lineColor);
   for (i = 0; i < thickness; i++) {
     g.drawLine(x, y + height - i - 1, x + width, y + height - i - 1);
   }
   g.setColor(oldColor);
 }

 public Insets getBorderInsets(Component c) {
   return new Insets(0, 0, gap, 0);
 }

 public Insets getBorderInsets(Component c, Insets insets) {
   insets.left = 0;
   insets.top = 0;
   insets.right = 0;
   insets.bottom = gap;
   return insets;
 }

 /**
  * Returns the color of the border.
  */
 public Color getLineColor() {
   return lineColor;
 }

 /**
  * Returns the thickness of the border.
  */
 public int getThickness() {
   return thickness;
 }

 /**
  * Returns whether or not the border is opaque.
  */
 public boolean isBorderOpaque() {
   return false;
 }

 public int getGap() {
   return gap;
 }

}

The code above generates the following result.

Create custom Bottom Border in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer