62,614
社区成员
发帖
与我相关
我的任务
分享
import java.text.DecimalFormat;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Dazi extends JPanel implements KeyListener {
JLabel lbl1, lbl2, lbl3, lbl4, msg;
String str = "When Isaac Newton said\"Every action has an equal and opposite reaction\"he demonstrated he knew a lot about physics and absolutely nothing about women.";
String substr = "";
JTextArea txt;
int index = 0;
double count = 0;
DecimalFormat form1 = new DecimalFormat("0.000"); // 指定数字输出格式保留3位小数
public static void main(String args[]) {
JFrame f = new JFrame("练习英文打字");
Dazi da = new Dazi();
JPanel pane = da.init();
JPanel p = new JPanel();
f.getContentPane().add(pane);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 250);
f.setVisible(true);
}
public JPanel init() {
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEADING));
lbl1 = new JLabel("When Isaac Newton said\"Every action");
lbl2 = new JLabel("has an equal and opposite reaction\"");
lbl3 = new JLabel("he demonstrated he knew a lot about physics");
lbl4 = new JLabel("and absolutely nothing about women.");
msg = new JLabel("请输入上面的文字");
txt = new JTextArea(5, 25);
txt.setEditable(false);
txt.setLineWrap(true); // 设置自动换行
/* txt.setBorder(BorderFactory.cteateEtchedBorder(EtchedBorder.RAISED)); */
p.add(lbl1);
p.add(lbl2);
p.add(lbl3);
p.add(lbl4);
p.add(msg);
p.add(txt);
txt.addKeyListener(this);
return p;
}
public void KeyTyped(KeyEvent e) {
count++;
if (index != str.length()) {
if (String.valueOf(e.getKeyChar()).equals(
str.substring(index, index + 1))) {
substr = str.substring(0, index + 1);
txt.setText(substr);
index++;
}
}
if (index == str.length())
msg.setText("您的错误率为:" + form1.format(1 - index / count));
}
public void KeyPressed(KeyEvent e) {
}
public void KeyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}