在Java中,如何使用来自另一个类的数据在JPanel上绘图?

时间:2015-12-01 22:58:50

标签: java swing

有没有办法使用其他类的数据在JPanel上绘图?这是我试过的代码:

class overlay extends JPanel {

    public void paintComponent(Graphics g, lineStore data) {        
        super.paintComponent(g);
        this.setBackground(Color.WHITE);
        g.setColor(Color.BLUE);
        for (int i = 0; i < data.length; i++) {
            g.drawLine(data[i].x1,data[i].y1,data[i].x2,data[i].y2);
        }
    }

}

1 个答案:

答案 0 :(得分:3)

你走了:

class overlay extends JPanel {

private lineStore data;

public overlay(lineStore data) {
    this.data = data;
}

public void paintComponent(Graphics g) {        
    super.paintComponent(g);
    this.setBackground(Color.WHITE);
    g.setColor(Color.BLUE);
    for (int i = 0; i < data.length; i++) {
        g.drawLine(data[i].x1,data[i].y1,data[i].x2,data[i].y2);
    }
}

}

要使用它,请执行以下操作:

lineStore data; //create lineStore here
overlay panel = new overlay(data);
panel.repaint();