2012-02-03 157 views
1

我正在Java中使用SWT进行测验。我有一个包含问题和答案的课程。在主课程中,当用户通过对话框输入他的姓名和问题的数量并按OK时,测验开始。 我有一个for循环应该遍历每个问题,例如,第一次迭代应该给用户一个问题,它应该等到用户通过文本框输入答案。当用户接下来按下按钮时,如果答案是正确的,他会得到一条消息,然后转到第二次迭代等等。 我的问题是,每次他开始测验时,for循环都不会等待用户输入和按钮预设操作,并直接进入最后一个问题(for循环的最后一次迭代)。Java - 当用户按下按钮时暂停for循环并继续迭代

有人可以给我写一个例子,我应该怎么做?

回答

1

您需要更改问题编号以回应事件。以下是伪代码:

private int count = 0; 

startMethod() 
{ 
    askQuestion(0); 
} 

onTextInput() 
{ 
    checkAnswer(); 
    count++; 
    askQuestion(count); 
} 
1

这是完整的代码。希望你会发现它有用。

import org.eclipse.core.internal.databinding.Pair; 
import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Shell; 
import org.eclipse.swt.widgets.Label; 
import org.eclipse.swt.SWT; 
import org.eclipse.swt.widgets.Text; 
import org.eclipse.swt.widgets.Button; 
import org.eclipse.swt.events.SelectionAdapter; 
import org.eclipse.swt.events.SelectionEvent; 

public class Quiz { 

    protected Shell shell; 
    private Text text; 
    private Pair[] questions ; 
    private int number_of_question = 10; 
    private int current_question = 0; 
    public static void main(String[] args) { 
     try { 
      Quiz window = new Quiz(); 
      window.open(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void open() { 
     Display display = Display.getDefault(); 
     createContents(); 
     shell.open(); 
     shell.layout(); 
     while(!shell.isDisposed()) { 
      if(!display.readAndDispatch()) { 
       display.sleep(); 
      } 
     } 
    } 

    protected void createContents() {  
     createQuiz(); 

     shell = new Shell(); 
     shell.setSize(450,300); 
     shell.setText("SWT Application"); 

     final Label lblTheQuestion = new Label(shell, SWT.NONE); 
     lblTheQuestion.setBounds(45, 38, 124, 15); 
     lblTheQuestion.setText((String) questions[current_question].a); 

     text = new Text(shell, SWT.BORDER); 
     text.setBounds(45, 88, 76, 21); 

     Button btnNext = new Button(shell, SWT.NONE); 
     btnNext.addSelectionListener(new SelectionAdapter() { 

      @Override 
      public void widgetSelected(SelectionEvent e) { 

       if(text.getText().equals((String) questions[current_question].b)) { 
        new Thread(new Runnable() { 
         public void run() {         
           shell.getDisplay().syncExec(new Runnable() {         
            @Override 
            public void run() { 
             current_question++; 
             lblTheQuestion.setText((String) questions[current_question].a); 
             lblTheQuestion.redraw();  
            } 
           }); 
         } 

        }).start(); 
       }  
      } 
     }); 
     btnNext.setBounds(188, 55, 75, 25); 
     btnNext.setText("Next"); 
    } 
    private void createQuiz() { 
     questions = new Pair[number_of_question]; 
     for(int i = 0; i<number_of_question; i++) { 
      questions[i] = new Pair("Question"+i,""+i); 
     } 

    } 

}