文件你可以用记事本编辑,当然要注意保存到与程序文件一个包里面,不然就会抛出异常
package xiancheng9;
import java.io.*;
public class Example12_14 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WinSolve win=new WinSolve();
win.setTitle("限时回答问题");
win.setFile(new java.io.File("1.text"));
win.setMax(8);
}
}
package xiancheng9;
import java.awt.*;import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class WinSolve extends JFrame implements ActionListener,ItemListener{
File textFile;
int max=8;
int maxtime=max,score=0;
JLabel showTime,showScore;
JTextArea textShow;
JCheckBox Abox,Bbox,Cbox,Dbox;
JButton restart;
String CorrectAnswer;
javax.swing.Timer time;
FileReader inOne;
BufferedReader inTwo;
WinSolve(){
time=new javax.swing.Timer(1000,this);
textShow=new JTextArea(2,16);
setLayout(new FlowLayout());
showTime=new JLabel(" ");
showScore=new JLabel(" ");
Abox=new JCheckBox("A");
Bbox=new JCheckBox("B");
Cbox=new JCheckBox("C");
Dbox=new JCheckBox("D");
Abox.addItemListener(this);
Bbox.addItemListener(this);
Cbox.addItemListener(this);
Dbox.addItemListener(this);
restart =new JButton("再做一遍");
add(showTime);
add(new JLabel("问题:"));
add(textShow);
add(Abox);
add(Bbox);
add(Cbox);
add(Dbox);
add(showScore);
restart.setEnabled(false);
add(restart);
restart.addActionListener(this);
setBounds(100,100,200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void setMax(int n){
max=n;
}
public void setFile(File f){
textFile=f;
score=0;
try{
inOne=new FileReader(textFile);
inTwo=new BufferedReader(inOne);
readQuestion();
restart.setEnabled(false);
}
catch(IOException exp){
System.out.print("没有题目");
}
}
public void readQuestion(){
textShow.setText(null);
try{
String s=null;
while((s=inTwo.readLine())!=null){
if(!s.startsWith("-")){
textShow.append("\n"+s);
}
else {
s=s.replaceAll("-", "");
CorrectAnswer=s;
break;
}
}
time.start();
if(s==null){
inTwo.close();
restart.setEnabled(true);
textShow.append("题目完毕");
time.stop();
}
}
catch(IOException exp){}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==time){
showTime.setText("剩:"+maxtime+"秒");
maxtime--;
if(maxtime<0){
maxtime=max;
readQuestion();
}
}
else
if(e.getSource()==restart){
setFile(textFile);
}
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
JCheckBox box=(JCheckBox)e.getSource();
String str=box.getText();
Boolean booOne=box.isSelected();
Boolean booTwo=str.compareToIgnoreCase(CorrectAnswer)==0;
if(booOne&&booTwo){
score++;
showScore.setText("分数:"+score);
time.stop();
maxtime=max;
readQuestion();
}
else
{
showScore.setText("分数:"+score);
}
box.setSelected(false);
}
}