# 一點心情，寫java結課考試之前

/* * Created on 2005-4-14 * 視窗分為上下兩個區,分別運行兩個線程,一個在上面的地區中顯示 * 由右向左遊動的字串,另一個在下面的地區從左向右遊動的字串. */

/** * 作者:龍震嶽 * 學院:電腦與資訊技術學院 * 班級:計科0308 */

import java.awt.*;import java.util.*;import javax.swing.*;

class MoveFrame extends JFrame {

private static final long serialVersionUID = 1L;

private JPanel jp1 = new JPanel(), jp2 = new JPanel();  /**  * 定義兩個Canvas的內部類。  * 剛開始的用後用panel，發現畫完之後會留有痕迹，  * 每次畫完還要擦除，很不爽，所以改用Canvas，呵呵。  **/  private Canvas cv1 = new Canvas() {  private static final long serialVersionUID = 1L;

int x = 0, y = 70, maxX = 640, minX = 0;

boolean isToEnd1 = false;  // 碰到邊就返回的演算法，很簡單的啦。  public void paint(Graphics g) {   if (!isToEnd1) {    g.drawString("向右移動", x, y);    x += 10;    if (x >= maxX)     isToEnd1 = true;   } else {    g.drawString("向左移動", x, y);    x -= 10;    if (x <= minX)     isToEnd1 = false;   }  } },   cv2 = new Canvas() {  private static final long serialVersionUID = 1L;

int x = 640, y = 70, maxX = 640, minX = 0;

boolean isToEnd2 = false;

public void paint(Graphics g) {   if (!isToEnd2) {    g.drawString("向左移動", x, y);    x -= 10;    if (x <= minX)     isToEnd2 = true;   } else {    g.drawString("向右移動", x, y);    x += 10;    if (x >= maxX)     isToEnd2 = false;   }  } };

private int x1 = 0, x2 = 0;

private Thread t1, t2;  // 定義兩個隨機的變數，使它們休眠的時間不一樣 private Random rand1 = new Random();

private Random rand2 = new Random();

private void move1() {  t1 = new Thread() {   public void run() {    while (true) {     cv1.repaint();     x1 = rand1.nextInt(100);     try {      sleep(x1);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   }  };  t1.start(); }

private void move2() {  t2 = new Thread() {   public void run() {    while (true) {     cv2.repaint();     x2 = rand2.nextInt(100);     try {      sleep(x2);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   }  };  t2.start(); }

public MoveFrame() {  Container cp = getContentPane();  cp.setLayout(new GridLayout(2, 1));  cp.add(cv1);  cp.add(cv2);  move1();  move2();  this.setTitle("線程作業");  this.pack();  this.setSize(640, 280);  this.setVisible(true); }}

public class MovingString {

public static void main(String[] args) {  MoveFrame mf = new MoveFrame(); }}

## Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD