我正在尝试创建一个如下所示的自定义JButton: 这是我的代码,我覆盖JButton和抽象边框:
class PolygonButton extends JButton {
public PolygonButton(String value) {
super(value);
}
Polygon polygon;
@Override
public boolean contains(int x, int y) {
int width = getSize().width;
int height = getSize().height;
int xPoints[] = { width / 5, width, width, width - width / 5, 0, 0, width / 5 };
int yPoints[] = { 0, 0, height - height / 5, height, height, height / 5, 0 };
if (polygon == null || !polygon.getBounds().equals(getBounds())) {
polygon = new Polygon(xPoints, yPoints, xPoints.length);
}
return polygon.contains(x, y);
}
}
我覆盖抽象边框的代码:
class CustomBorder extends AbstractBorder {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
super.paintBorder(c, g, x, y, width, height);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
int xPoints[] = { width / 5, width, width, width - width/5, 0, 0 };
int yPoints[] = { 0, 0, height - height/5, height, height, height/5 };
g2d.draw(new Polygon(xPoints, yPoints, xPoints.length));
}
}
我最终得到的是右侧包含的按钮,但边框虽然具有所需边框的一般形式,但在顶部和左侧都是切断的,并且非常薄。
有没有更好的方法来处理自定义边框,我最终会得到一个与上图相同的JButton并且边框厚度可变?