2013-05-30 20:29:32Morris
[JAVA][作業] 從 JFrame 改用 JApplet
功能規定:
用 JApplet 代替 JFrame 完成此程式 :
1. 程式啟動時,隨機產生 10 個 JLabel 在視窗中不同位置。(不用判斷重疊)
2. JLabel 的內容為小寫字母 a~z 。
3. 當鍵盤輸入英文字母時要消除對應到的 JLabel 。
package ce1002.E8.s100502205;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
public class E8 extends JApplet {
public void init() {
this.setSize(500, 500);
this.getContentPane().add(new GPanel());
}
}
class GPanel extends JPanel implements KeyEventDispatcher {
private JLabel[] letter = new JLabel[26];
private JLabel clock = new JLabel("00:00:00");
private boolean[] hit = new boolean[26];
private int[] X = new int[26];
private int[] Y = new int[26];
private Font font = new Font("Serif", Font.BOLD, 30);
int hitCount;
long StartTime;
boolean restart;
public void randomBoard() {
for (int i = 0; i < 10; i++) {
int x = 0;
do {
x = (int) (Math.random() * 26);
} while (hit[x] == true);
hit[x] = true;
X[x] = (int) (Math.random() * 450);
Y[x] = (int) (Math.random() * 450);
}
hitCount = 10;
StartTime = System.currentTimeMillis();
}
public GPanel() {
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(this);
for (int i = 0; i < letter.length; i++) {
letter[i] = new JLabel("" + (char) ('a' + i));
letter[i].setFont(font);
this.add(letter[i]);
}
clock.setFont(font);
this.add(clock);
randomBoard();
Timer timer = new Timer();
timer.schedule(new Heart(), 500, 50);
}
public class Heart extends TimerTask {
public void run() {
if (restart == true)
return;
long ProcessTime = System.currentTimeMillis() - StartTime;
ProcessTime /= 10;
int msecond = (int) (ProcessTime % 100);
ProcessTime /= 100;
int second = (int) (ProcessTime % 60);
ProcessTime /= 60;
int minute = (int) (ProcessTime);
clock.setText(String.format("%02d:%02d:%02d", minute, second,
msecond));
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 26; i++) {
letter[i].setVisible(hit[i]);
letter[i].setLocation(X[i], Y[i]);
}
clock.setLocation(10, 10);
}
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_RELEASED)
return false;
char key = e.getKeyChar();
if (key >= 'a' && key <= 'z') {
if (hit[key - 'a'] == true)
hitCount--;
hit[key - 'a'] = false;
}
if (key >= 'A' && key <= 'Z') {
if (hit[key - 'A'] == true)
hitCount--;
hit[key - 'A'] = false;
}
if (hitCount == 0 && restart == false) {
long ProcessTime = System.currentTimeMillis() - StartTime;
ProcessTime /= 10;
int msecond = (int) (ProcessTime % 100);
ProcessTime /= 100;
int second = (int) (ProcessTime % 60);
ProcessTime /= 60;
int minute = (int) (ProcessTime);
restart = true;
JOptionPane.showMessageDialog(this, String.format(
"Clear %02d:%02d:%02d", minute, second, msecond));
restart = false;
randomBoard();
}
repaint();
return false;
}
}