?? hitshrew.java
字號:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HitShrew extends JFrame {
ImageIcon hamtaro = new ImageIcon(getClass().getResource("Hamtaro.jpg"));
int n=5; //width & height
int gameLength=30; //seconds
int score;
long startTime;
ShrewButton[] button;
JLabel status;
public HitShrew() {
super("Hit Shrew");
Container c=getContentPane();
JPanel gamePanel = new JPanel();
gamePanel.setLayout(new GridLayout(n,n));
button = new ShrewButton[n*n];
for(int i=0; i<n*n; i++) {
button[i] = new ShrewButton(hamtaro,this);
button[i].setNumber(n);
button[i].setBackground(Color.lightGray);
gamePanel.add(button[i]);
}
status = new JLabel("Prepared!");
c.add(gamePanel, BorderLayout.CENTER);
c.add(status, BorderLayout.SOUTH);
setBounds(150,150,500,500);
show();
init();
}
public void init() {
JOptionPane.showMessageDialog(this,"箇稱!");
startTime = System.currentTimeMillis()/1000;
for(int i=0;i<n*n;i++) {
button[i].setStartTime(startTime);
button[i].setGameLength(gameLength);
new Thread(button[i]).start();
}
long t=0;
while( (t=System.currentTimeMillis()/1000) < startTime+gameLength) {
t = startTime+gameLength - t;
status.setText("Time:" + t + " Scores:" + score*10);
Thread.yield();
}
status.setText("Finish! You get " + score*10 + " points!");
}
public void setScore(int score) {
this.score+=score;
}
public static void main(String[] args) {
HitShrew obj = new HitShrew();
obj.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class ShrewButton extends JButton implements Runnable,ActionListener {
long startTime;
long endTime;
ImageIcon ic;
boolean flag=false;
int score;
int n;
HitShrew controller;
public ShrewButton(ImageIcon ic, HitShrew controller) {
this.ic = ic;
this.controller = controller;
addActionListener(this);
}
public void setNumber(int n) {
this.n = n;
}
public void setStartTime(long second) {
startTime = second;
}
public void setGameLength(long second) {
endTime=startTime+second;
}
public void run() {
while ( System.currentTimeMillis()/1000 < endTime) {
int flag = (int) (Math.random()*n*n);
setBackground(Color.lightGray);
if (flag == 1) {
setIcon(ic);
setFlag(true);
}
else {
setIcon(null);
setText("");
setFlag(false);
}
try {
Thread.sleep(750);
}
catch(InterruptedException e) {
System.out.println("Unexpected exception!");
}
setIcon(null);
setText("");
setFlag(false);
}
setIcon(null);
setBackground(Color.lightGray);
setText(score + " hit!");
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
public void actionPerformed(ActionEvent e) {
if ( this.flag == true) {
setFlag(false);
setText("HIT!");
setBackground(Color.red);
setIcon(null);
score++;
controller.setScore(1);
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -