0

您好,我正在 Java 中创建一个应用程序(练习),我必须在其中更改绘图类中变量的颜色。当应用程序启动并且我在颜色变量上运行 sysout 时,它显示为空,但是当我按下鼠标右键时,它会在控制器类中更改颜色,但在我的绘图类中没有。有人可以看看并告诉我什么我做错了吗?

这是一段代码

这是绘图类的相关部分

    private Color color;
private ArrayList<Point> p = new ArrayList<Point>();

public Drawing(Color color) {
    this.color = color;
    System.out.println("color  " + color);
}

public void draw(Graphics g) {
    for(int i = 0; i < p.size(); i++) {
        g.setColor(color);
        g.fillRect(p.get(i).x, p.get(i).y, 10, 10);
    }
}

这是我的控制器的相关代码。

Color color; // kleur vasthouden
Drawing draw; // class definieren
private ArrayList<Drawing> tekening = new ArrayList<Drawing>();
int x, y;

public DrawingPanel() {
    setBackground(Color.WHITE); // zorg voor een witte achtergrond.
    this.addMouseListener(this); // control de mouselistener
    draw = new Drawing(color);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    draw.draw(g);
}

@Override
public void mouseClicked(MouseEvent e) {

    if(e.getButton() == MouseEvent.BUTTON1) {
        Point k = new Point(e.getX(), e.getY());

        draw.addPoint(k);
        System.out.println("punt gezet op " + k);
    }
    if(e.getButton() == MouseEvent.BUTTON3) {
        color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0);
        System.out.println("new color " + color);
    }
    repaint();
}

我希望有人能弄清楚我做错了什么..

4

4 回答 4

2

color你从来没有真正为我能看到的代码中的任何地方分配一个初始值。您仅在发生鼠标事件时设置它。

if(e.getButton() == MouseEvent.BUTTON3) {
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0);
    System.out.println("new color " + color);
}

我假设除了打印出这种颜色之外,您还希望将其设置为您的绘图类,然后触发重绘。

于 2012-12-14T15:23:39.503 回答
1

在您的类中添加一个setter方法,Drawing并在鼠标右键单击计算后传递实际颜色:

public void setColor(Color color) {
   this.color = color;
}

在控制器中:

if(e.getButton() == MouseEvent.BUTTON3) {
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0);
    System.out.println("new color " + color);
    draw.setColor(color);
}
于 2012-12-14T15:26:16.867 回答
0

由于它们是单独的类,因此它们color中的每一个都是一个单独的对象。
如果在您的Drawing班级中更改color为公共,则可以设置color为在控制器中创建的新颜色。

color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0);
draw.color = color;

您还可以在绘图类中创建一个设置器,并使用它来设置控制器的颜色。

public setColor(Color color) {
    this.color = color;
}

此外,在构造函数中将颜色设置为任何值都会阻止它打印为 null。

于 2012-12-14T15:26:54.013 回答
0

在您的控制器中,您有一个颜色属性,在右键单击时,您设置它,但您从未在绘图类上设置它。尝试 :

if(e.getButton() == MouseEvent.BUTTON3) {
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0);
draw.setColor(color);
于 2012-12-14T15:26:58.007 回答