这个程序借鉴的网上的一个程序一样。
public class SampleSWTUI { public Shell showGUI(final Display display) { Shell shell = new Shell(display); shell.setLayout(new GridLayout(3,true)); shell.setText("Sample SWT UI"); new Label(shell, SWT.NONE).setText("User Name: "); final Text nameText = new Text(shell, SWT.BORDER); nameText.setText (""); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); data.horizontalSpan = 2; nameText.setLayoutData(data); new Label(shell, SWT.NONE).setText("Password: "); final Text passwordText = new Text(shell, SWT.BORDER); // final Text passwordText = new Text(shell, SWT.BORDER|SWT.PASSWORD); passwordText.setText (""); data = new GridData(SWT.FILL, SWT.FILL, true, false); data.horizontalSpan = 2; passwordText.setLayoutData(data); Button loginButton = new Button (shell, SWT.PUSH); loginButton.setText ("Login"); data = new GridData(SWT.FILL, SWT.FILL, true, false); data.horizontalSpan = 3; loginButton.setLayoutData(data); loginButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String user = nameText.getText(); String password = passwordText.getText(); System.out.println("\n\n\n"); if (user.equals("Favonius") && password.equals("abcd123")) { System.out.println("Success !!!"); } else { System.err.println("What the .. !! Anyway it is just a demo !!"); } } }); shell.pack(); shell.open(); return shell; } public static void main(String [] args) { Display display = new Display(); Shell shell = new SampleSWTUI().showGUI(display); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
public class SWTBotDemo { static SWTBotButton loginButton; static SWTBotText userText; static SWTBotText passwordText; static SWTBot bot; static Display display; static Shell shell; @BeforeClass public static void beforeClass() throws Exception { SWTBotPreferences.PLAYBACK_DELAY = 1000; display = Display.getDefault(); shell = new SampleSWTUI().showGUI(display); bot = new SWTBot(shell); loginButton = bot.button("Login"); userText = bot.textWithLabel("User Name: "); passwordText = bot.textWithLabel("Password: "); } @Test public void testLogin() { bot.sleep(1000); userText.setFocus(); userText.setText("aaaaaaaa"); passwordText.setFocus(); passwordText.setText("11111111"); userText.setFocus(); userText.setText("bbbbbbbb"); passwordText.setFocus(); passwordText.setText("2222222"); userText.setFocus(); userText.setText("ccccccc"); passwordText.setFocus(); passwordText.setText("3333333"); bot.sleep(1000); loginButton.setFocus(); loginButton.click(); bot.sleep(1000); userText.setFocus(); userText.setText("Favonius"); bot.sleep(1000); passwordText.setFocus(); passwordText.setText("abcd123"); bot.sleep(1000); assert(userText.getText().equals("abcd123")); loginButton.setFocus(); loginButton.click(); bot.sleep(3000); // while (!shell.isDisposed()) { // if (!display.readAndDispatch()) display.sleep(); // } // // display.dispose(); } }