【问题标题】:Java draw line on a JPanel via methodJava通过方法在JPanel上画线
【发布时间】:2023-03-12 00:21:01
【问题描述】:

我想找到一种方法来定义一个方法,该方法在调用时会在 JPanel 上画一条线。覆盖 PaintComponent 时,我无法弄清楚这一点。 它应该看起来像这样......

class MyCanvas extends JPanel {
    My Canvas () {
    ...
    }
    public void drawLineOnCanvas(x1, y1, x2, y1) {
    ...code which draws a line
    }
}

【问题讨论】:

  • 调用paintComponent中的方法,你需要把paintComponent中的Graphics上下文传递给这个方法

标签: java swing user-interface graphics


【解决方案1】:

paintComponent 调用该方法,您需要将Graphics 上下文从paintComponent 传递给该方法

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    drawLine(g, fromX, fromY, toX, toY);
}

public void drawLineOnCanvas(Graphics g, x1, y1, x2, y1) {
...code which draws a line
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2023-03-22
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多