对于这种特殊情况,您需要创建自己的边框。
以下是带有渐变边框类的示例:
public static class GradientBorder implements Border
{
private Insets margin;
public GradientBorder ( int top, int left, int bottom, int right )
{
super ();
margin = new Insets ( top, left, bottom, right );
}
public void paintBorder ( Component c, Graphics g, int x, int y, int width, int height )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( new GradientPaint ( x, y, Color.RED, x + width, y, Color.BLUE ) );
Area border = new Area ( new Rectangle ( x, y, width, height ) );
border.subtract ( new Area ( new Rectangle ( x + margin.left, y + margin.top,
width - margin.left - margin.right, height - margin.top - margin.bottom ) ) );
g2d.fill ( border );
}
public Insets getBorderInsets ( Component c )
{
return margin;
}
public boolean isBorderOpaque ()
{
return true;
}
}
当然,你可以指定任何其他的梯度方向、颜色等。如果需要,你也可以将它们的初始化放到构造函数中。要使用它,你只需要设置边框(在任何JComponent继承类中):
jComponent.setBorder ( new GradientBorder ( 25, 50, 25, 50 ) );
你可以使用这种方法创建任何你想要的边框,包括不同的颜色/动画/形状等。
此外,如果你想要创建半透明边框(例如使用半透明颜色,带有圆角等形状),请确保isBorderOpaque() 方法返回true,否则你将不得不处理组件重绘问题。