【发布时间】:2016-03-31 00:10:00
【问题描述】:
例如,我正在尝试画一条线,并在每次按“c”时更改颜色。我有 5 个布尔变量
boolean redColor = false;
boolean blueColor = false;
boolean greenColor = false;
boolean yellowColor = false;
boolean defaultColor = false;
我有一个变量int counter = 0,我用它来增加函数keyPressed(KeyEvent e)。因为我有 5 个变量,所以当计数器达到值 6 时,我重置计数器并从 1 重新开始,颜色为红色。在paint() 方法中,我检查上面的那些布尔值,如果它们是真的,我改变颜色。
第一次,直到计数器重置,我可以改变颜色,但计数器重置后,我的颜色不会改变。我将在这里写下到底发生了什么:
counter = 1 => color red
counter = 2 => color blue
counter = 3 => color green
counter = 4 => color yellow
counter = 5 => color black(default)
counter = 6 => reset color back to 1
直到这里一切正常,但是当计数器重置并再次递增时,对于任何计数器值,颜色仍然相同,黑色。
我将在这里写一部分代码,也许不是最好的方法,但我是 AWT 的新手。我希望为此使用awt。感谢您阅读我的帖子。
public void paint(Graphics g)
{
if(mousePressed == true)
{
g.drawLine(x1,y1,x2,y2);
if(redColor == true)
{
g.setColor(Color.RED);
g.drawLine(x1,y1,x2,y2);
}
if(blueColor == true)
{
g.setColor(Color.BLUE);
g.drawLine(x1, y1, x2, y2);
}
if(greenColor == true)
{
g.setColor(Color.GREEN);
g.drawLine(x1, y1, x2, y2);
}
if(yellowColor == true)
{
g.setColor(Color.YELLOW);
g.drawLine(x1, y1, x2, y2);
}
if(defaultColor == true)
{
g.setColor(Color.BLACK);
g.drawLine(x1, y1, x2, y2);
}
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyChar() == 'c')
{
counter ++;
if(counter == 1)
redColor = true;
if(counter == 2)
blueColor = true;
if(counter == 3)
greenColor = true;
if(counter == 4)
yellowColor = true;
if(counter == 5)
{
defaultColor= true;
}
else if(counter == 6)
counter = 1;
}
}
【问题讨论】: