200 likes | 358 Views
Event Driven, GUI. Avshalom Elmalech Eliahu Khalastchi 2010. Java runs upon a VM Graphical libraries / components Belong to the operating system (OS) Are different for different operating systems Not written in Java GUI – Graphical User Interface GUI is challenging for Java
E N D
Event Driven, GUI Avshalom Elmalech Eliahu Khalastchi 2010
Java runs upon a VM Graphical libraries / components Belong to the operating system (OS) Are different for different operating systems Not written in Java GUI – Graphical User Interface GUI is challenging for Java Access to the OS’s graphical components Programming for multi-platforms Introduction
Introduction • Awt - Abstract Windowing Toolkit (1995) • The first GUI for Java • Weighty – calls OS’s components • Lowest common denominatorproblem • Uses components that areavailable in every platform • Effective yet ugly
Introduction • Swing /JFC (1998) • The official GUI for Java (SUN) • Every component is written in Java (light weight) • Tires to mimic OS’s look • Will work under anyplatform • But the look & feel arenot exactly the same
Introduction • SWT – Standard Widget Toolkit (IBM, 2001) • Tires to enjoy both worlds • Uses the OS’s components when available • Uses Java implementationwhen they are not • OS’s look & feel • Requires swt.jar • Implemented for eachplatform
Introduction • Today’s lecture is about SWT programming • In the recitation we will get familiar with a visual editor – that writes the code for us • Here, we will get familiar with the code itself • And more importantly, the concept ofEvent Driven Programming
Introduction – event driven • It is an application architecture technique • The flow of the program is determined by events i.e, • Sensors input (robot, software agent) • User’s action (mouse click, key pressed) • Messages from other programs / threads • The application has a main loop which is clearly divided down to two sections: • The first is event selection (or event detection) • The second is event handling
Introduction – event driven • Event-driven programming is widely used in GUIs • It has been adopted by most commercial widget toolkits as the model for interaction • How it works? • First, methods called event handlers are written • Then registered to listen to certain events • The events trigger the event handlers
Main event loop import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; publicclass GUI { publicstaticvoid main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Hello, world!"); shell.open(); // Set up the event loop. while (!shell.isDisposed()) { if (!display.readAndDispatch()) { // If no more entries in the event queue display.sleep(); } } display.dispose(); } } • Every swt program requires display and at least one shell • Shell is a window that can contain graphical objects • Here we instance them • open() opens the window • While the window is open • Upon an occurrence of an event, readAndDispatch calls the event’s handler • Otherwise the display sleeps • And finally disposed
layouts shell.setSize(400, 300); new Button(shell, SWT.PUSH).setText("Push Button"); new Button(shell, SWT.CHECK).setText("Check Button"); new Button(shell, SWT.TOGGLE).setText("Toggle Button"); new Button(shell, SWT.RADIO).setText("Radio Button"); shell.pack(); • We’ve created 4 instances of different buttons, and set their text • How are they arranged? • shell.setLayout(Layout l) • FillLayout - puts all the widgets in a horizontal or a vertical line • RowLayout – the same with wrapping • GridLayout – defines a grid which is actually a table shell.setLayout(new FillLayout(SWT.HORIZONTAL)); shell.setLayout(new RowLayout(SWT.HORIZONTAL)); shell.setLayout(new GridLayout(2,true));
Form Layout With FormData dependencies to the window / other components can be defined shell.setLayout(new FormLayout()); Button button1 = new Button(shell, SWT.PUSH); button1.setText("button1"); FormData formData = new FormData(); formData.left = new FormAttachment(20); formData.top = new FormAttachment(20); button1.setLayoutData(formData); Button button2 = new Button(shell, SWT.PUSH); button2.setText("button number 2"); formData = new FormData(); formData.left = new FormAttachment(button1, 0, SWT.CENTER); formData.top = new FormAttachment(button1, 0, SWT.BOTTOM); button2.setLayoutData(formData);
Widgets Text fields and lables shell.setLayout(new GridLayout()); new Label(shell, SWT.NONE).setText("Enter your Name, Password"); new Text(shell, SWT.BORDER).setText("Name"); new Text(shell, SWT.PASSWORD | SWT.BORDER).setText("password"); new Text(shell, SWT.READ_ONLY).setText("type your comments"); new Text(shell, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | SWT.BORDER).setText("\n\n\n"); String[] items = "RV1 RV2 Aibo R2D2".split(" "); List list = new List(shell, SWT.SINGLE | SWT.BORDER); list.setItems(items); list.setLocation(10, 10); list.setSize(100, 80); list.select(2); List String[] items = "RV1 RV2 Aibo R2D2".split(" "); Combo combo1 = new Combo(shell, SWT.DROP_DOWN); combo1.setItems(items); Combo combo2 = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY); combo2.setItems(items); Combo
Widgets for(int i = 0; i < 6; i++) new Button(shell, SWT.RADIO).setText("option " + (i + 1)); Let’s say we want to choose one option of 1..3 and one of 4..5, how can we do it? Group group1 = new Group(shell, SWT.SHADOW_OUT); Group group2 = new Group(shell, SWT.SHADOW_OUT); group1.setText("group 1"); group1.setLayout(new GridLayout(3, true)); for(int i = 0; i < 3; i++) new Button(group1, SWT.RADIO).setText("option " + (i + 1)); group2.setText("group 2"); group2.setLayout(new GridLayout(3, true)); for(int i = 3; i < 6; i++) new Button(group2, SWT.RADIO).setText("option " + (i + 1)); We’ll create them under different groups. Each group can have its own layout
Widgets • Canvas is a painting board • Used for low level graphical 2d paintings • We can create anything – with hard work • The painting is an event handler • Because it needs to react to window changes • Steps for painting: • Create a canvas • Add an instance of the paintListener interface
Widgets Canvas c=new Canvas(shell,SWT.BORDER); c.addPaintListener(newPaintListener() { publicvoid paintControl(PaintEvent e) { // Get the canvas and its size Canvas canvas = (Canvas) e.widget; int maxX = canvas.getSize().x; int maxY = canvas.getSize().y; int mx=maxX/2,my=maxY/2; int r=Math.min(maxX,maxY)/10; e.gc.drawOval(mx-r, r, 2*r, 2*r); e.gc.drawArc(mx-r/2, 2*r, r, r-r/3, 180, 180); e.gc.drawLine(mx, 3*r, mx, 6*r); e.gc.drawLine(mx, 3*r, mx/2, 5*r); e.gc.drawLine(mx, 3*r, mx+mx/2, 5*r); e.gc.drawLine(mx, 6*r, mx/2, 9*r); e.gc.drawLine(mx, 6*r, mx+mx/2, 9*r); e.gc.drawString("I love SWT!", mx+r+5, 2*r); } }); We’ve instanced an anonymous class the implemented the PaintListener interface – that defines the paintControlmethod that receives a PaintEvent instance upon call
Event Handling – button push shell.setLayout(new GridLayout(2,true)); final Button b=new Button(shell,SWT.PUSH); b.setText("hello"); final Text t=new Text(shell, SWT.BORDER); Listener listener = new Listener() { publicvoid handleEvent(Event event) { if(event.widget==b) t.setText("hello"); } }; b.addListener(SWT.Selection, listener); • widgetscan listen to events • an event is caused by the user (i.e, click) • to handle the event we need to define a Listener and implement the handleEvent() method • some listeners are pre-defined • for example: finalButtonb=newButton(shell,SWT.PUSH);b.setText(“hello");finalTextt=newText(shell,SWT.BORDER);b.addSelectionListener(newSelectionListener(){publicvoidwidgetSelected(SelectionEventevent){text.setText(“hello");}publicvoidwidgetDefaultSelected(SelectionEventevent){text.setText(“hello");}});
Event Handling – mouse events final Label l=new Label(shell,SWT.BORDER); l.setSize(100,20); final Canvas c=new Canvas(shell,SWT.BORDER); c.setSize(300,300); c.setLocation(0, 21); c.addPaintListener(new PaintListener() { publicvoid paintControl(PaintEvent e) { e.gc.drawOval(x-10, y-10, 20,20); } }); c.addMouseMoveListener(new MouseMoveListener(){ publicvoid mouseMove(MouseEvent e) { x=e.x; y=e.y; c.redraw(); } }); c.addMouseListener(new MouseListener(){ publicvoid mouseDoubleClick(MouseEvent e) { c.setBackground(display.getSystemColor(( new Random()).nextInt(36))); } publicvoid mouseDown(MouseEvent e) { l.setText("mouse down"); } publicvoid mouseUp(MouseEvent e) { l.setText("mouse up"); } });
Ready components • Ready components • FileDialog • FontDialog • ColorDalog • etc… FileDialog fd=new FileDialog(shell,SWT.OPEN); fd.setText("open"); fd.setFilterPath("E:/workspace/89210 part3"); String[] filterExt = { "*.txt", "*.java", ".xml", "*.*" }; fd.setFilterExtensions(filterExt); String selected = fd.open(); MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION| SWT.YES | SWT.NO); messageBox.setMessage("Do you really want to exit?"); messageBox.setText("Exiting Application"); int response = messageBox.open(); if (response == SWT.YES) System.exit(0);
Working with Threads & SWT • Updating a SWT component from another thread will result in a runtime exception • We need to use display.(a)syncExec(Runnable r) Thread operationThread = new Thread() { publicvoid run() { // UI Updating procedures go here ... } }; Thread operationThread = new Thread() { publicvoid run() { display.asyncExec / syncExec(new Runnable() { publicvoid run() { // UI Updating procedures go here ... } }); } };
Useful links • http://www.eclipse.org/swt/ • http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm code example • http://www.ibm.com/developerworks/opensource/library/os-ecvisual/ a visual editor for eclipse from IBM