下面是我正在讨论的代码:
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()
方法交换其中两个“正方形”的颜色?我在想,我正在实现它的正确轨道上,但以前没有做过这样的颜色。
发布于 2012-11-09 07:32:00
您将需要使用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;
}
发布于 2012-11-09 07:33:43
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-09 07:43:28
在默认的构造函数调用中,你有两个几乎相同的构造函数Board()和Board(h,w),su:
public Board() //constructor
{
Board(200,200);
}
如果使用此方法,将来将只需要编辑一个构造函数,而不是同时编辑两个。
https://stackoverflow.com/questions/13299735
复制相似问题