如何交换2个对象的颜色

时间:2012-11-08 23:30:38

标签: java colors

这是我的问题代码:

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()
{



}

如何使用.getColor()方法交换其中2个“方块”的颜色?我认为我已经走上了正确的道路,但是之前不必用颜色做这样的事情。

2 个答案:

答案 0 :(得分:1)

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

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

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

编辑:

您似乎需要为color的Block类添加getter和setter,所以只需添加:

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

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

答案 1 :(得分: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;
}