这是完整的代码。希望你会发现它有用。
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);
}
}
}