import java.awt.*;
import java.awt.event.*;
class MyButton extends Button
implements ActionListener
{ int x=10,y=10,i=0;
Color color[]={Color.red,Color.yellow,Color.green};
Color c=color[0];
MyButton()
{ setSize(38,85);
setBackground(Color.cyan);
addActionListener(this);
}
public void paint(Graphics g)
{ g.setColor(c);
g.fillOval(x,y,20,20);
}
public void update(Graphics g)
{ g.clearRect(x,y,20,20);
paint(g);
}
public void actionPerformed(ActionEvent e)
{ i=(i+1)%3;
c=color[i];
y=y+23;
if(y>56)
y=10;
repaint();
}
}
class WindowCanvas extends Frame
{ WindowCanvas()
{ MyButton button=new MyButton();
setLayout(null);
add(button);
button.setLocation(30,30);
setBounds(60,125,100,200);
setVisible(true);
validate();
}
}
public class Example7_24
{ public static void main(String args[])
{ new WindowCanvas();
}
}一、此程序中 validate();这句要不要好像都一样。请问validate();何时用?并用例子说明。
二、此程序模拟红绿灯,可快速点击时会出现两个灯都亮的情况,请问这是问什么?如何改进?
import java.awt.event.*;
class MyButton extends Button
implements ActionListener
{ int x=10,y=10,i=0;
Color color[]={Color.red,Color.yellow,Color.green};
Color c=color[0];
MyButton()
{ setSize(38,85);
setBackground(Color.cyan);
addActionListener(this);
}
public void paint(Graphics g)
{ g.setColor(c);
g.fillOval(x,y,20,20);
}
public void update(Graphics g)
{ g.clearRect(x,y,20,20);
paint(g);
}
public void actionPerformed(ActionEvent e)
{ i=(i+1)%3;
c=color[i];
y=y+23;
if(y>56)
y=10;
repaint();
}
}
class WindowCanvas extends Frame
{ WindowCanvas()
{ MyButton button=new MyButton();
setLayout(null);
add(button);
button.setLocation(30,30);
setBounds(60,125,100,200);
setVisible(true);
validate();
}
}
public class Example7_24
{ public static void main(String args[])
{ new WindowCanvas();
}
}一、此程序中 validate();这句要不要好像都一样。请问validate();何时用?并用例子说明。
二、此程序模拟红绿灯,可快速点击时会出现两个灯都亮的情况,请问这是问什么?如何改进?
{ g.clearRect(x,y,20,20);
paint(g);
}这里,清除区域大一些,把所有灯的区域都清除掉。g.clearRect(10,10,20,20+23+23);
MFC中validate() 是更新数据的意思,就是修改了变量,要把结果在界面上显示出来,就调用该函数更新数据;