150 likes | 297 Vues
Datalogi A 7: 20/10. CS A. Event driven programs. Many things may happen: Pressing a button Selecting values with sliders, lists etc. Type text in fields Mouse clicks on a canvas Timers Menus Window closing, resizing. JEventQueue. My little trick…
E N D
Datalogi A 7: 20/10 CS A
Event driven programs Many things may happen: • Pressing a button • Selecting values with sliders, lists etc. • Type text in fields • Mouse clicks on a canvas • Timers • Menus • Window closing, resizing
JEventQueue My little trick… Usual event-driven programming in Swing requires: • Inheritance • Interface • Inner classes
JEventQueue JEventQueue events = new JEventQueue(); events.listenTo(button1,"button1"); events.listenTo(button2,"button2"); ... while(true){ EventObject event = events.waitEvent(); String name=events.getName(event); if(name.equals("button1")){ ... }else if(name.equals("button2")){ ... }else ... }
Event loop JEventQueue events=new JEventQueue(); events.listenTo(button1,"celcius"); events.listenTo(button2,"fahrenheit"); while(true){ EventObject event=events.waitEvent(); String name=events.getName(event); if(name.equals("celcius")){ double f=Double.parseDouble(field2.getText()); field1.setText(""+(f-32)/1.8); }else if(name.equals("fahrenheit")){ double c=Double.parseDouble(field1.getText()); field2.setText(""+(c*1.8+32)); } }
Selections: RadioButton: isSelected() CheckBox: isSelected() Spinner: getValue() Slider. getValue() ComboBox: getSelectedItem() List: getSelectedValue()
Text components Generate lots of events: You press ’a’ • Key pressed event • Key typed event • Text field changed event • Key released event
Text Components Ignore most of them except: • Typing a key that corresponds to a character • Pressing a control key: Arrows, Page up/down, function keys etc.
Mouse events Draw circles where you click and lines where you drag. int x0=0,y0=0; while(true){ EventObject event=events.waitEvent(); if(events.isMouseEvent(event)){ int x=events.getMouseX(event); int y=events.getMouseY(event); if(events.isMousePressed(event)){x0=x;y0=y;} if(events.isMouseClicked(event)) canvas.drawOval(x0-5,y0-5,10,10); if(events.isMouseReleased(event)) canvas.drawLine(x0,y0,x,y); } }
Timers startTimer(miliseconds,name) stopTimer(name)
Menus frame.setJMenuBar( events.jmenubar(new Font("Arial",Font.PLAIN,18), events.jmenu("File",'F’, events.jmenuitem("New",'n',events.control('N')), events.jmenuitem("Open",'o',events.control('O')), events.jmenuitem("Save",'s',events.control('S')), events.jmenuitem("Save as",'a', events.control('A')), events.jmenuitem("Exit",'x',events.control('Q')) ), events.jmenu("Edit",'E', .. ), events.jmenu("View",'V', ) ) )
Menus Mnemonic: Press Alt-F to get File menu then press ’s’ to save Accelerator key: Press Control-s to save
Window events Events when closing or resizing a window Bring up a dialog when you close a window so that the user can confirm whether the user wants to exit the program.