gpt4 book ai didi

java - Swing - 不规则形状的边框

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:30 24 4
gpt4 key购买 nike

我是 Swing 新手,想知道如何更好地绘制这个形状:

complicated shape

我有两种想法

  1. 绘制常规矩形并为其编写自定义边框?
  2. 绘制常规矩形+复合边框(包含2或3个边框)。但是在这里我没有成功在形状内绘制边框,有可能吗?是这样的: two bordersfigure.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(outside top,left,bottom, right, Color.WHITE)), createMatteBorder(inside top,left,bottom, right, Color.WHITE)),其中内边框是小长方形,外面是大长方形,不知道可以吗???

请提供建议,我们将不胜感激!

最佳答案

看看 Java 2D API .它可以帮助您绘制复杂的形状。

例如

class IrregularShape extends JComponent {

private int strokeWidth;

IrregularShape(int strokeWidth){
this.strokeWidth = strokeWidth;
}

@Override
protected void paintComponent(Graphics g) {
Graphics2D newGraphics = (Graphics2D) g.create();

Insets borderInsets = new Insets(0, 0, 0, 0);
Border border = getBorder();
if (border != null) {
borderInsets = border.getBorderInsets(this);
}

BasicStroke basicStroke = new BasicStroke(strokeWidth);
newGraphics.setStroke(basicStroke);

int x = getX() + borderInsets.left + strokeWidth;
int y = getY() + borderInsets.top + strokeWidth;
int width = getWidth() - x - borderInsets.right - strokeWidth;
int height = getHeight() - y - borderInsets.bottom - strokeWidth;

Double outterRactangleDouble = new Rectangle2D.Double(x, y, width, height);

Area outterRectangle = new Area(outterRactangleDouble);

Area innerRectangle = new Area(outterRactangleDouble);
AffineTransform affineTransform = new AffineTransform();
affineTransform.scale(0.5, 0.5);
affineTransform.translate(x + width * 0.10, y + height * 1.2);

innerRectangle.transform(affineTransform);
outterRectangle.subtract(innerRectangle);
newGraphics.draw(outterRectangle);

}

}

public class MainFrame {

public static void main(String[] args) {
JFrame frame = new JFrame("Irregular Shape");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Container contentPane = frame.getContentPane();
contentPane.add(new IrregularShape(3));

frame.setSize(640, 150);

frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

}

结果 enter image description here

而且它还可以调整大小

enter image description here

关于java - Swing - 不规则形状的边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34286151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com