Creating Your Own Border
Creating your own border is simple when you extend the
AbstractBorder
class. You need to define three things: how to draw the
border, whether it is opaque, and what its insets are. To accomplish
this, you must implement paintBorder(
)
, both isBorderOpaque( )
methods, and getBorderInsets( )
. The
hard part of coming up with your own border is doing something creative
with the Graphics
primitives in the
paintBorder( )
method. A reminder:
make sure that you paint only in the insets region that you define for
yourself. Otherwise, you could be painting over the component you intend
to border.
Let’s take a look at a simple border:
// CurvedBorder.java // import java.awt.*; import javax.swing.border.*; public class CurvedBorder extends AbstractBorder { private Color wallColor = Color.gray; private int sinkLevel = 10; public CurvedBorder( ) { } public CurvedBorder(int sinkLevel) { this.sinkLevel = sinkLevel; } public CurvedBorder(Color wall) { this.wallColor = wall; } public CurvedBorder(int sinkLevel, Color wall) { this.sinkLevel = sinkLevel; this.wallColor = wall; } public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { g.setColor(getWallColor( )); // Paint a tall wall around the component. for (int i = 0; i < sinkLevel; i++) { g.drawRoundRect(x+i, y+i, w-i-1, h-i-1, sinkLevel-i, sinkLevel); g.drawRoundRect(x+i, y+i, w-i-1, h-i-1, sinkLevel, sinkLevel-i); g.drawRoundRect(x+i, y, w-i-1, h-1, sinkLevel-i, sinkLevel); g.drawRoundRect(x, y+i, ...
Get Java Swing, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.