0

这是我有问题的代码:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

import sun.java2d.loops.DrawRect;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class Board extends JPanel implements MouseListener
{
//instance variables
private int width;
private int height;
private Block topLeft;
private Block topRight;
private Block botLeft;
private Block botRight;

public Board()  //constructor
{
    width = 200;
    height = 200;
    topLeft=new Block(0,0,width/2-10,height/2-10,Color.RED);
    topRight=new Block(width/2,0,width/2-10,height/2-10,Color.GREEN);
    botLeft=new Block(0,height/2,width/2-10,height/2-10,Color.BLUE);
    botRight=new Block(width/2,height/2,width/2-10,height/2-10,Color.YELLOW);
    setBackground(Color.WHITE);
    setVisible(true);
    //start trapping for mouse clicks
    addMouseListener(this);
}

//initialization constructor
public Board(int w, int h)  //constructor
{
    width = w;
    height = h;
    topLeft=new Block(0,0,width/2-10,height/2-10,Color.RED);
    topRight=new Block(width/2,0,width/2-10,height/2-10,Color.GREEN);
    botLeft=new Block(0,height/2,width/2-10,height/2-10,Color.BLUE);
    botRight=new Block(width/2,height/2,width/2-10,height/2-10,Color.YELLOW);
    setBackground(Color.WHITE);
    setVisible(true);
    //start trapping for mouse clicks
    addMouseListener(this);
}



public void update(Graphics window)
{
    paint(window);
}

public void paintComponent(Graphics window)
{
super.paintComponent(window);
topRight.draw(window);
topLeft.draw(window);
botRight.draw(window);
botLeft.draw(window);


}

public void swapTopRowColors()
{
Color temp = topLeft.getColor(topRight);
topRight.setColor(temp);
repaint();
 }

public void swapBottomRowColors()
{



}

public void swapLeftColumnColors()
{



}

public void swapRightColumnColors()
{



}

我将如何使用该方法交换其中 2 个“正方形”的颜色.getColor()?我在想我在实现它的正确轨道上,但以前不必用颜色做这样的事情。

4

3 回答 3

1

您将需要使用setColor(),但在此之前您需要创建其中一种颜色的温度。

public void swapColors(Block g1, Block g2) {
    Color c = g1.getColor();
    g1.setColor(g2.getColor());
    g2.setColor(c);
    repaint();
}

同样使用此方法标头,您可以从对象中交换两种颜色,Block而无需为每种组合使用不同的方法,只需将要交换的两种颜色作为参数传递即可。

编辑:

看来您需要为您的 Block 类添加一个 getter 和 setter color,所以只需添加:

public Color getColor() {
    return this.color; 
}

public void setColor(Color c) {
    this.color = c;
}
于 2012-11-08T23:31:59.517 回答
1
public void swapTopRowColors()
{
    Color temp = topLeft.getColor(topRight);
    topLeft.setColor(topRight.getColor()); //<-- line you're missing
    topRight.setColor(temp);
    repaint();
}

===以下评论===

你需要在你的Block类中添加getter和setter:

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
}
于 2012-11-08T23:33:42.547 回答
0

在默认构造函数调用中有 2 个几乎相同的构造函数 Board() 和 Board(h,w), su:

public Board()  //constructor
{
    Board(200,200);
}

如果您使用此方法,将来您将只需要编辑一个构造函数,而不是两个。

于 2012-11-08T23:43:27.990 回答