前言
一个简单的hello,java的图形化界面的入门程序。通过这个程序简单认识一下事件监听器和线程。在这里不做详细的说明,指体会监听器和线程的作用。
代码如下:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
* 运用线程实现字体闪烁
* 运用MouseMotionListener接口的MouseDragged()方法实现字符串的移动
* 运用ActionListener接口的actionPerforme()实现颜色的切换
*/
public class HelloJava {
public static void main(String[] args) {
JFrame frame = new JFrame("HelloJava");
frame.add(new HelloComponent("Hello,java!"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class HelloComponent extends JComponent implements MouseMotionListener ,ActionListener,Runnable{
String messages ;
JButton button;
int messagesx= 125;
int messagesy = 95;
int colorIndex;
static Color[] someColors = {Color.black,Color.red,Color.green,Color.blue,Color.magenta};
boolean blinkState; //闪烁状态
public HelloComponent4(String messages) {
this.messages=messages;
button = new JButton("Change color");
setLayout(new FlowLayout());
add(button);
button.addActionListener(this);
addMouseMotionListener(this);
Thread thread = new Thread(this); //创建线程,用this把自身传进去
thread.start();
}
public void paintComponent(Graphics g) {
g.setColor(blinkState?getBackground():currentColor()); //为闪烁线程提供服务,根据blinkstates的值,在背景色和当前颜色之间切换,从而实现闪烁。
g.drawString(messages, messagesx, messagesy);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== button)
changeColor();
}
synchronized private void changeColor() {
if(++colorIndex == someColors.length) //先对索引加1在判断,可能会有溢出的危险
colorIndex = 0;
setForeground(currentColor()); //设置前背景色
repaint();
}
synchronized private Color currentColor() {
return someColors[colorIndex];
}
public void mouseMoved(MouseEvent e) {//MouseMotionListener接口中的方法,函数体为空也必须对其实现
}
public void mouseDragged(MouseEvent e) {
messagesx = e.getX();
messagesy = e.getY();
repaint();
}
public void run() {//必须要有try进行捕获异常,否则会报错,此异常为中断异常InterruptedException
try {
while(true) {
blinkState = !blinkState;
repaint();
Thread.sleep(300); //线程睡眠时间为1/3秒,每秒钟闪烁3次
}
}catch (InterruptedException e) {
}
}
}