import java.awt.event.*
import java.applet.*
public class ColorChange extends Applet implements MouseListener
{Button btn=new Button("变色")
public void init()
{btn.addMouseListener(this)
this.add(btn)}//将鼠标事件注册
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
setBackground(Color.white)}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseClicked(MouseEvent e){
setBackground(Color.green)
repaint()
}
}
package com.test5import java.applet.*
import java.awt.Color
import java.awt.GridLayout
import java.awt.event.*
import javax.swing.*
public class ChangeColor extends Applet implements Runnable{
static JButton button1, button2, button3, button4
public void init() {
button1 = new JButton()
button2 = new JButton()
button3 = new JButton()
button4 = new JButton()
JFrame change = new JFrame("变色")
setLayout(new GridLayout(2, 2))
add(button4)
add(button1)
add(button2)
add(button3)
setSize(300, 300)
ActionListener command = new ActionListener() {
public void actionPerformed(ActionEvent event) {
//run()//直接调用run()方法看不到任何效果,因为程序执行时间太快了,如果采用线程睡眠(即暂停1S),就OK
Thread t1=new Thread(new ChangeColor())
t1.start()
}
}
button1.addActionListener(command)
button2.addActionListener(command)
button3.addActionListener(command)
button4.addActionListener(command)
//初始化即起动线程,然后单击按钮再启动线程,都能看到效果。
Thread t=new Thread(this)
t.start()
}
public void run() {
Color b[] = { Color.cyan, Color.yellow, Color.red, Color.blue,
Color.green, Color.black, Color.DARK_GRAY, Color.MAGENTA,
Color.PINK, Color.darkGray }
JButton a[] = { button1, button2, button3, button4 }
try {
for (int i = 0i <4i++){
a[i].setBackground(b[(int) (Math.random() * 10)])
Thread.sleep(1000)
}
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)