Tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 13 Java AWT – Part II (Optional): Chapter 13Java AWT – Part II(Optional)Lecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:discuss the use of Java in animating World Wide Web applicationsshow how to write Java applets introduce Java graphical components (e.g. Textfields, Buttons, and Labels)show how Java programs can be made to react to user actions on Java graphical componentsshow how Java applications can be run from inside web browsersFramesA frame is a window with a title bar and a borderThe Frame class is a subclass of Container classContainer class objects may have other components (e.g. Buttons) added to them using the add method A typical Java GUI will create and display one or more framesTo make a frame visible the message setVisbible(true) must be sent to the frameLayout ManagersGoverns how components are arranged inside a Container objectThe Container method setLayout allows the programmer to sp...
36 trang |
Chia sẻ: honghanh66 | Lượt xem: 718 | Lượt tải: 0
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 13 Java AWT – Part II (Optional), để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 13Java AWT – Part II(Optional)Lecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:discuss the use of Java in animating World Wide Web applicationsshow how to write Java applets introduce Java graphical components (e.g. Textfields, Buttons, and Labels)show how Java programs can be made to react to user actions on Java graphical componentsshow how Java applications can be run from inside web browsersFramesA frame is a window with a title bar and a borderThe Frame class is a subclass of Container classContainer class objects may have other components (e.g. Buttons) added to them using the add method A typical Java GUI will create and display one or more framesTo make a frame visible the message setVisbible(true) must be sent to the frameLayout ManagersGoverns how components are arranged inside a Container objectThe Container method setLayout allows the programmer to specify which layout manager (e.g. FlowLayout) is desired for a particular container objectThe size of a Container object should be set explicitly by the programmer as wellCan use pack() to set size to accommodate preferred sizes of components)Frame Examplepublic class TwoButtons { Frame f; Button redButton, blueButton; public TwoButttons() { f = new Frame(“Two Buttons Frame”); redButton = new Button(“Red”); blueButton = new Button(“Blue”); f.setLayout(new Flowlayout()); f.add(redButton); f.add(blueButton); f.pack(); f.setVisible(true); }}UML NotationThe filled diamond represents compositionThis shows that the class TwoButtons contains a class Frame which contains a class ButtonsA good UML diagram only shows the classes and associations that are important to understanding the architectureThis UML diagram does not include super classes like Component or Container Using InheritanceIt is possible to use inheritance to allow TwoButtons to become a frame in its own rightNote that the UML diagram will show TwoButtons as a subclass of FrameYou will need to use super()to set the frame titleFrame Inheritance Examplepublic class TwoButtons extends Frame { Button redButton, blueButton; public TwoButttons() { super(“Two Buttons Frame”); redButton = new Button(“Red”); blueButton = new Button(“Blue”); f.setLayout(new Flowlayout()); f.add(redButton); f.add(blueButton); f.pack(); f.setVisible(true); }}Other Simple Java ComponentsLabelcontains some text that can be set using a constructor or the method setLabelTextFielda box into which the user can type texttext can be edited (backspace, delete, etc.)text can be retrieved using getText()text can be set using setText()Java AWT Event ModelIncluding reactive program components involves:Having the class header declare itself as implementing the ActionListener interfaceTypically in the class constructor the class instance registers itself as being interested in listening for events from a newly created componentOne method (e.g. actionPerformed) of the ActiveListener interface is definedFrame Inheritance Examplepublic class classname extends Frame implements ActionListener { Button buttonname; public classname() { buttonname = new Button(“button label”); add(buttonname); buttonname.ActionListener(this); } public void actionPerformed(ActionEvent e) { what to do when button is pushed }}UML Notation for Button ProgramAbstract class indicated by italicizing the class nameImplements association (concrete class) indicated by line with a closed arrowheadUML stereotype (constructors, accessor, interface implementation methods) indicated by enclosing a descriptive word inside guillements > Closing the WindowYou must implement the WindowListener and its seven required methods windowActivated, windowClosed, windowClosing, windowDeactivated, windowIconified, windowDeiconified, windowOpenedThis is usually done in a programmer defined class like ClosableFrame and all classes needing these services would extend ClosableFrameUsing Conditionals with Reactive Componentspublic void actionPerformed(ActionEvent e) { double fahr, cent; // check for user input in tFahr TextField if (e.getSource() == tFahr) { fahr = new Double(tFahr.getText()),doubleValue(); cent = 5.0 * (fahr – 32.0) / 9.0; tCent.setText(cent + “”); // update tCent TextField } else { cent = new Double(tCent.getText()),doubleValue(); fahr = 9.0 * cent / 5.0 + 32.0; tFahr.setText(fahr + “”); }CheckboxesUsed to allow user to select one or more itemsAlways has a labelProgram often needs to react to the user selection(s)Declaration example:Checkbox powerBrakes = new Checkbox(“Power Brakes”);Checkbox powerSteering = new Checkbox(“Power Steering”);Checkbox ac = new Checkbox(“Air Conditioning”);add(powerBrakes);add(powerSteering);add(ac);Programming CheckboxesProgram is declared with implements ItemListener Checkbox is registered by calling addItemListener Event is handled using itemStateChanged argument type ItemEventThe ItemEvent argument is used to tell which item triggered the event by calling getSourceRadio ButtonsA group of Checkboxes in which only one item can be selected at a timeImplemented using a Java CheckboxGroupItems are declared initially as selected (true) or unselected (false) Example:CheckboxGroup gender;Checkbox maleCheck = new Checkbox(“Male”, gender, true);Checkbox femaleCheck = new Checkbox(“Female”, gender, true);Processing Radio Buttonspublic void compute() { boolean female = (gender.getSelectedCheckbox() == femaleCheck); if ((bodyMassIndex > 27.8) || (female && (bodyMassIndex > 27.3)) lHigh.setText(“This is considered high”); else 1High.setText(“this is not considered high”);}Drawing in a FrameTo draw in a Frame you need to the override the frame’s paint method:public void paint(Graphics g)Graphics objects are defined by the Java runtime system and are used for drawing operationsThe Frame should be considered to be a grid with upper left coordinates (0,0) and positive coordinates (x,y) for the lower rightTypical Drawing Codepublic class MyDrawing extends ClosableFrame { public MyDrawing() { } public void paint(Graphics g) { g.drawLine(); g.drawImage(); }}Repaint and UpdateThe paint method requires an argument and actionPerformed does not know what to supply when calledThe method repaint will clear the Frame and then call paint along with supplying the needed missing argumentYou can prevent clearing the Frame when using repaint by overriding the method update before calling repaintPanel and Canvas Classes The Panel class is container subclass that is used to reserve a rectangular portion of a Frame to place other componentsThe Canvas class is not a Container subclass, but does allow you to reserve a portion of a Frame to draw inComparing Layout ManagersFlowLayoutDefault frame layoutComponents are placed on new line only when neededGridLayoutFrame is declared as a grid of fixed size (e.g. two rows and three columns)Components are placed in the grid left to right and top to bottomBorderLayoutFrame is divided into north, south, east, west, and centerComponents are placed by the programmer in the desired location using the add methodTypical GUI FramePanel p1 = new Panel(); p1.setLayout(new GridLayout(2,1)); p1.add(component); p1.add(component);Panel p2 = new Panel(); p2.setLayout(); p2.add(component); setLayout(new BorderLayout());add(“North”, p1);add(“Center”, p2);ScrollbarsThe leftmost position of a horizontal scrollbar corresponds to some integer value and the rightmost position corresponds to a larger integer valueScrollbars can be displayed verticallyUser movement optionsClicking either end button causes bubble to move in unit incrementsClicking the are between bubble and end button causes movement in 10 unit incrementsClicking and dragging the bubble in the desired directionHypertext Markup LanguageHTML – SkeletonPage TitleText and graphics to display in browserHTML Text DisplaysDisplays a centered heading in browser windowNaploean ITo identify text paragraphs to be displayedIn my spare time I like to do origami and spend quiet evenings at home with my wife Josephine. HTML Using Pictures and LinksDisplays a centered pictureTo display a text link to another web pageJosephineTo display a picture link to another web pageApplet Tag and HTMLTo include a Java applet as part of an HTML documentJava applet shell for BodyMass.classimport java.applet.*;public class BodyMass extends Applet { public_html void start() { new BodyMass(); }}Transforming a Java Program into an AppletSet the size you want the applet to be in the HTML fileAdd the import statement to the Java code java.applet.*;Change header from extends Frame to extends AppletChange constructor heading to public void start();Eliminate any Java code that is meaningless in applets
Các file đính kèm theo tài liệu này:
- chapter13_6711.ppt