先上圖,看看效果,
點選run時設定的文字會一直随機跳動,點選stop停止,并顯示目前的文字
package com.diego.main.test;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RandomName // implements extends Thread
implements ActionListener, Runnable {
// 設置一個標記
private boolean flag = false;
private JFrame randomFrame = new JFrame("隨機獲取名字");
// 建立一個Panel對象。
private JPanel randomPanel = new JPanel();
private TextField tf = new TextField();
private JButton randomButton1 = new JButton("Run");
private JButton randomButton2 = new JButton("Stop");
private String[] name = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
public RandomName() {
// 向JPanel容器中添加三個元件
randomPanel.add(tf);
randomPanel.add(randomButton1);
randomPanel.add(randomButton2);
randomFrame.add(randomPanel);
// 取得螢幕的寬度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
// 取得螢幕的高度
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
// 設定元件不可改變大小
randomFrame.setResizable(false);
// 設定關閉窗體時結束程式
randomFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 設定元件大小
randomFrame.setSize(, );
// 設定元件位置
randomFrame.setLocation((width - ) / , (height - ) / );
// 設定元件大小和位置
// randomFrame.setBounds(30, 30, 250, 120);
// 設定元件可見
randomFrame.setVisible(true);
addListener();
}
private void addListener() {
randomButton1.addActionListener(this);
randomButton2.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object obj = e.getSource();
if (obj == randomButton1) {
synchronized (this) {
notify();
flag = true;
}
}
if (obj == randomButton2) {
synchronized (this) {
flag = false;
}
}
}
public void run() {
int length = name.length;
while (true) {
try {
if (!flag) {
synchronized (this) {
this.wait();
}
}
Random myRandomName = new Random();
int RN = myRandomName.nextInt(length);
tf.setText(name[RN]);
Thread.sleep();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
RandomName rn = new RandomName();
Thread t1 = new Thread(rn);
t1.start();
}
}