Created
October 31, 2018 13:30
-
-
Save astrophysik928/65575852acd18232fc3d258685af3721 to your computer and use it in GitHub Desktop.
swingでタイピングゲーム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.BorderLayout; | |
import java.awt.Color; | |
import java.awt.Font; | |
import java.awt.event.KeyEvent; | |
import java.awt.event.KeyListener; | |
import java.util.Random; | |
import javax.swing.JFrame; | |
import javax.swing.JLabel; | |
public class KeyTyping extends JFrame implements KeyListener { | |
JLabel jl; | |
static int count = 0; | |
static final String[] words = { "extends", "implements", "this", "break", "for", "switch", "while" }; | |
public static void main(String[] args) { | |
new KeyTyping(); | |
} | |
KeyTyping() { | |
// JFrame設定 | |
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
this.setSize(400, 400); | |
this.setTitle("タイピング"); | |
// ラベル設定 | |
jl = new JLabel("first"); // インスタンス生成 | |
jl.setFont(new Font(null, Font.PLAIN, 40)); | |
jl.setHorizontalAlignment(JLabel.CENTER); | |
jl.setOpaque(false); | |
// イベント発生 | |
addKeyListener(this); | |
// 処理後のラベルをコンテナの中央に配置 | |
this.getContentPane().add(BorderLayout.CENTER, jl); | |
this.setVisible(true); | |
} | |
@Override | |
public void keyPressed(KeyEvent e) { | |
// TODO 自動生成されたメソッド・スタブ | |
String str = jl.getText(); | |
int text_length = str.length(); | |
int num = 0; | |
char head_text = str.charAt(num); | |
// 判定 | |
if (head_text == e.getKeyChar()) { | |
// 入力が正しい場合 | |
jl.setForeground(Color.BLACK); | |
num++; | |
// ラベルの先頭より2文字以降を切り取って、ラベルにセット | |
jl.setText(str.substring(num)); | |
} else { | |
// 入力が不正な場合 | |
jl.setForeground(Color.RED); | |
} | |
// 文字入れ替え | |
// ラベルの文字の長さが0になった時 | |
if (num == text_length) { | |
jl.setText(RandomString()); | |
} | |
} | |
@Override | |
public void keyReleased(KeyEvent arg0) { | |
// TODO 自動生成されたメソッド・スタブ | |
} | |
@Override | |
public void keyTyped(KeyEvent arg0) { | |
// TODO 自動生成されたメソッド・スタブ | |
} | |
// 乱数生成 | |
public String RandomString() { | |
Random ran = new Random(); | |
int number = ran.nextInt(words.length); | |
return words[number]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment