1

将 Graphics2D 对象的 BasicStroke 更改为 1 以外的任何值会导致它在启动时不在 JPanel 的中心绘制任何东西。

这是一个 JFrame 上的 JPanel。这是我项目的基本思想,但不是全部。

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    if(this.centered){
        this.myShape.setCenterX(this.getWidth()/2);
        this.myShape.setCenterY(this.getHeight()/2);
    }
    g2.setStroke(new BasicStroke(3)); //new BasicStroke(1) works fine
    g2.draw(this.myShape);
}

当您单击并拖动 myShape 时,myShape 将立即跳到中心。但是当我最初编译并运行它时,如果笔画不是 1,paintComponent() 会在屏幕中心上方约一厘米处绘制它。

我的居中方式有问题吗?我定义了 MyShape 类,所以那里可能有错误。也许中心和绘图点之间的距离是JPanel和JFrame顶部之间的空间?我如何解决它?

编辑:添加图片

http://s21.postimage.org/dfpmz73et/Untitled_1.png 第一个形状正好在我想要的地方。另外两个在我想要的地方。但无论笔划大小如何,从中心的位移似乎都是相同的。

4

1 回答 1

1

是的,我相信这是形状的正常行为。它假定轮廓为 1 个像素。因此,当您知道要更改基本笔划大小时,您需要更改中心计算。就像是:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    BasicStroke stroke = new BasicStroke(3);
    int adjustment = stroke.getLineWidth() - 1;

    if(this.centered){
        this.myShape.setCenterX(this.getWidth() + adjustment / 2);
        this.myShape.setCenterY(this.getHeight() + adjustment / 2);
    }
    g2.setStroke(stroke);
    g2.draw(this.myShape);
}
于 2013-03-17T19:32:53.307 回答