Download presentation
Presentation is loading. Please wait.
Published byBritton Andrews Modified over 9 years ago
1
CompSci 230 S2 2015 Software Construction Applets & AWT
2
Agenda Applets Abstract Windowing Toolkit (AWT) Basic AWT windows Basic AWT user interface controls Button, checkbox, radio button, list box, scrollbars Processing events in GUI controls Reading: Getting Started with Graphics https://docs.oracle.com/javase/tutorial/2d/basic2d/ https://docs.oracle.com/javase/tutorial/2d/basic2d/ Java AWT Tutorial 22 112
3
Java Applets: a simple GUI framework Applet framework (web browser) Application code init( ) start( ) paint( )stop( ) destroy( ) Applet init( ) start( ) paint( ) stop( ) destroy( ) Examples: C:\Program Files\Java\jdk1.8.0_45\demo\applets 113
4
Applet Class Applet defines a set of so-called lifecycle methods that are expected to be implemented by sucbclasses. init( ) – executed when the web browser loads the Applet subclass code. This method is often implemented to acquire resources – threads, sockets etc. start( ) – executed when the applet should start its execution. paint( ) – called whenever the applet is to paint itself, (e.g. a person has moved on the tic-tac-toe game) has changed. Typically called multiple times. stop( ) – called when the user leaves the web page that contains the applet. destroy( ) – called by the browser on exit. This gives the applet the chance to clean up – e.g. close sockets. 114
5
Example: Blink public class Blink extends java.applet.Applet {... public void init() {... public void start() {... public void paint(Graphics g) {... public void stop() {... 115
6
Example: Simple Simple.java Simple.html Command: appletviewer Simple.html... public class Simple extends Applet { StringBuffer buffer; public void init() {... Example: Simple.java 116
7
A bstract W indowing T oolkit Java’s AWT is a simple framework for developing graphical user interfaces (GUIs) Key AWT packages include: java.awt Contains core GUI component classes Components are also known as widgets and may be “simple” (e.g. buttons, textfields) or “composite” (e.g. windows, frames, panels) Includes layout managers that layout composite components’ children java.awt.event Contains classes representing GUI events Events represent things like window closing and restoration, button presses, mouse movement, keystrokes, etc. Components generate events Provides listener interfaces Listener interfaces are provided that are intended to be implemented by application developers; listener objects can be notified of events 7 117
8
A Component is something that can be displayed on a GUI and with which a user can interact. A Window is a special Container that can be stacked, and moved to the front/back. A Frame is a special Window with a title, menubar, and border. Component is an abstract class. Generalisation Specialisation A Container is a special component that can nest other components, be they simple components (e.g. Buttons, Labels) or themselves Containers (e.g. Panels). add( ) is a polymorphic method; it can take as actual argument any kind of Component. Nothing in this class hierarchy is application specific. These classes provide a reusable resource that is extended to meet the needs of any particular application. 118
9
AWT framework Component an abstract class superclass of all GUI components except menu components and class CheckboxGroup repaint() schedules Component instance for repainting. The AWT framework will subsequently call paint( ) on the Component Container the superclass for all components that contain other components defines add(), for adding components to a container Component Container Object ButtonLabel Many other classes getSize( ) : int setSize( width : int, height : int ) : void setVisible( visible : boolean ) : void repaint( g : Graphics ) : void paint( g : Graphics ) : void addMouseListener( listener : MouseListener ) : void addKeyListener( listener : KeyListener ) : void setLayout( mgr : LayoutManager ) : void add( c : Component ) : void 119
10
AWT framework Window a top-level window with no border or menu bar rarely instantiated (its subclasses are more useful) Frame a window with a title bar can have a menu bar top-level window for Java AWT-based applications typically, main() creates an instance of Frame as its top-level application window, then adds GUI components to the frame default layout manager: BorderLayout Window Frame Container Dialog Many other classes setTitle( title : String ) : void setCursor( c : int ) : void setResizable( resizable : boolean ) : void setMenuBar( mb : MenuBar ) : void 1110
11
Frame class Creating and Using – Two Approaches: A fixed-size Frame: Use setSize() and setVisible(true) – for display A Frame that stretches to fit what it contains pack(), and setVisible(true) public class SimpleFixedFrame extends Frame { public SimpleFixedFrame(String title) { super(title); setSize(400, 300); setVisible(true); } public class StretchFrame extends Frame { public StretchFrame(String title) { super(title); add(new Button("hello"),BorderLayout.CENTER); pack(); setVisible(true);... Causes this Window to be sized to fit the preferred size and layouts of its subcomponents Example: SimpleFixedFrame.java StretchFrame.java 11
12
COMPSCI 230 Software Design & Construction12 Frame Panel Label TextField Label Panel Button Panel Component Container add( c : Component ) : void class Container extends Component { private List children; … public void add( Component c ) { children.add( c ); } Frame instance TextField instance Panel instance Button instance Button instance Label instance Panel instance Panel instance Label instance * 1112
13
PalindromeGUI Implementation import java.awt.*; public class PalindromeGUI extends Frame { public PalindromeGUI( ) { super( "Palindrome detector" ); setUp( ); setLayout(new FlowLayout()); // Method inherited from class Window – // causes this object to be sized according // to its preferred size, based on its // children components. pack( ); setVisible( true ); } public static void main( String[ ] args ) { PalindromeGUI = new PalindromeGUI( ); } // “Helper” method to create components. private void setUp() { // Create intermediate panels. Panel inputPanel = new Panel( ); Panel outputPanel = new Panel( ); Panel buttonPanel = new Panel( ); // Create simple components. Label prompt = new Label( "Word/phrase" ); TextField text = new TextField( 20 ); Label output = new Label( "Please enter a word/phrase" ); Button isPalindrome = new Button( "Is palindrome" ); Button quit = new Button( "quit" ); // Add components to intermediate panels. inputPanel.add( prompt ); inputPanel.add( text ); outputPanel.add( output ); buttonPanel.add( isPalindrome ); buttonPanel.add( quit ); // Add panels to this object. add( inputPanel ); add( outputPanel ); add( buttonPanel ); } Example: PalindromeGUI.java 1113
14
Traversing the nested structure 14 Frame instance TextField instance Panel instance Button instance Button instance Label instance Panel instance Panel instance Label instance class Container extends Component { private List children; … public void add( Component c ) { children.add( c ); } public void paint( Graphics g ) { for( Component c : children ) c.paint( ); } 1: paint( ) 2: paint( ) 3: paint( ) 4: paint( ) 5 6 7 8 9 1114
15
Layout management Aggregation 15 Container setLayout( mgr : LayoutManager ) : void doLayout( ) add( c : Component ) : void Component > LayoutManager layoutContainer( c : Container ) minimumLayoutSize( c : Container ) : Dimension preferredLayoutSize( c : Container ) : Dimension BorderLayoutBoxLayoutGridLayoutFlowLayout * 1 1115
16
button1 = new Button("Button 1 (PAGE_START)"); add(button1, BorderLayout.PAGE_START); button2 = new Button("Button 2 (CENTER)"); button2.setPreferredSize(new Dimension(200, 100)); add(button2, BorderLayout.CENTER); button3 = new Button("Button 3 (LINE_START)"); add(button3, BorderLayout.LINE_START); button4 = new Button("Long-Named Button 4 (PAGE_END)"); add(button4, BorderLayout.PAGE_END); button5 = new Button("5 (LINE_END)"); add(button5, BorderLayout.LINE_END); Layout Managers FlowLayout: Simplest, just one row BorderLayout: This scheme defines five areas for the component. All extra space is placed in the center area. BoxLayout, GridLayout, … 1116
17
Layout management 17 public class Container extends Component { … private List children; private LayoutManager ; public void setLayout( LayoutManager lm ) { layoutManager = lm; } public void doLayout( ) { layoutManager.layout( this ); } Frame instance TextField instance Panel instance Button instance Button instance Label instance Panel instance Panel instance Label instance 1: doLayout( ) 2: layoutContainer( this ) LayoutManager instance 1117
18
Painting Class Component implements a painting mechanism as follows: repaint( ) schedules the component to be painted and should not be overriden paint( ) is intended to be implemented by subclasses to perform subclass-specific painting E.g. A Button will paint itself as a button, a Panel will call paint on each child, etc. AWT Framework code Application code Framework detects that a window has moved from the minimised to restored state. It calls repaint( ) on the window component Framework calls paint( ) on the window component Framework calls paint( ) on component C AWT Framework code Application code Component paint( g : Graphics ) repaint( ) Framework triggers an event to which the application responds Application makes a repaint( ) request for a particular component, C 1118
19
Painting: System-triggered A GUI component is displayed by "painting" it on screen. System-triggered painting When? When the component is first shown When the component has been covered and uncovered This causes the component's paint() method to be called You should place the component's rendering code inside a the paint method When AWT invokes this method, the Graphics object parameter is pre-configured with the appropriate state for drawing on this particular component E.g. color => component’s foreground property public void paint(Graphics g) { Dimension size = getSize(); int d = Math.min(size.width, size.height); // diameter int ed = d/20; // eye diameter int x = (size.width - d)/2; int y = (size.height - d)/2; g.fillOval(x, y, d, d); g.setColor(Color.black); g.drawOval(x, y, d, d); g.fillOval(x+d/3-(ed/2), y+d/3-(ed/2), ed, ed); g.fillOval(x+(2*(d/3))-(ed/2), y+d/3-(ed/2), ed, ed); g.drawArc(x+d/4, y+2*(d/5), d/2, d/3, 0, -180); } Example: PaintDemo.java 1119
20
Painting: Application-triggered Application-triggered painting The program’s Java code determines that a component should be repainted when you change text, colors, … In your own program, when you want to repaint It calls repaint(), which queues a paint request You never call paint() directly! You always call repaint()! The event handler thread calls the component's paint() method MouseListener l = new MouseAdapter() { public void mousePressed(MouseEvent e) { MyButton b = (MyButton)e.getSource(); b.setSelected(true); b.repaint(); } }; 1120
21
Event handling Components generate events in response to user interaction To hook in application- specific responses to events, listeners are used A listener is an object that is registered with a component; in handling user interaction the component informs any registered listeners of events AWT Framework code Application code Framework detects a button press and generates an event Framework waits for next user interaction Framework detects a mouse drag and generates an event Registered listeners execute Button instanceListener instance event 1121
22
Event handling > ActionListener actionPerformed( e : ActionEvent ) : void > KeyListener keyPressed( e : KeyEvent ) : void keyReleased( e : KeyEvent ) : void keyTyped( e : KeyEvent ) : void > MouseListener mouseReleased( e : MouseEvent ) : void mouseClicked( e : MouseEvent ) : void mouseEntered( e : MouseEvent ) : void mouseExited( e : MouseEvent ) : void AWT framework Interface for receiving ActionEvents on a component Interface for receiving key stroke events on a component Interface for receiving mouse events (e.g. release, click, enter and exit) on a component Button addActionListener( listener : ActionListener ) ApplicationListener Application See API documentation for package java.awt.event for other listener interfaces Button instanceappListener : ApplicationListener 1: addActionListener( appListener ) 2: actionPerformed( ) 1122
23
Event Handling Event-driven programming is a programming style that uses a signal-and-response approach to programming The sending of an event is called firing the event The program itself no longer determines the order in which things can happen Instead, the events determine the order Typically, you do NOT call these event handlers yourself Inversion of Control (IOC): Don't call us, we'll call you Note: If you do want to capture events but forget to add a listener, no events will be captured (a common omission). 1123
24
Events, Listeners, Adapters and Handler Methods EventListener / AdapterHandler Methods ActionEventActionListeneractionPerformed AdjustmentEventAdjustmentListeneradjustmentValueChanged MouseEventMouseListener MouseAdapter mouseClicked mouseEntered mouseExited mousePressed mouseReleased KeyEventKeyListener KeyAdapter keyPressed keyReleased keyTyped ComponentEventComponentListener ComponentAdapter componentShown componentHidden componentMoved componentResized 1124
25
Buttons Constructors Button(String buttonLabel) Useful Methods getLabel/setLabel Retrieves or sets the current label Event Processing Methods addActionListener/removeActionListener Add/remove an ActionListener that processes ActionEvents in actionPerformed General Methods Inherited from Component getForeground/setForeground getBackground/setBackground getFont/setFont 1125
26
One Vs Two One button: Steps: Implements the ActionListener interface Create a button Add the button to the frame Add an ActionListener to the button Implement the actionPerformed method to handle the event More than one button: Steps are similar to the above But you must use e.getSource() in the actionPerformed event handler to check which button is pressed by the user. public class SimpleButton extends Frame implements ActionListener {... Button quit = new Button( "quit" ); add(quit); quit.addActionListener( this );... public void actionPerformed( ActionEvent e ) { System.exit( 0 ); } public void actionPerformed( ActionEvent e ) { if ( e.getSource( ) == quit ) { // System.exit( 0 ); } else if (e.getSource() == check) { count++; check.setLabel("" + count); } Example: SimpleButton.java 1126
27
TextField Constructors TextField(fieldLabel) Useful Methods getText/setText Retrieves or sets the text that is presented by this text component Event Processing Methods addActionListener/removeActionListener Add/remove an ActionListener that processes ActionEvents in actionPerformed Note: the user must press 'enter' inside the text field to activate the event. public class SimpleTextField extends Frame implements ActionListener {... value = new TextField("Enter a number"); copy = new TextField(20); value.addActionListener( this ); quit.addActionListener( this );... public void actionPerformed( ActionEvent e ) { copy.setText(value.getText()); }... Example: SimpleTextField.java 1127
28
public class PalindromeGUI2 extends Frame implements ActionListener { private TextField text; private Button isPalindrome, quit; private Label output; public PalindromeGUI2() { super( "Palindrome detector" ); … isPalindrome.addActionListener( this ); quit.addActionListener( this ); } public void actionPerformed( ActionEvent e ) { if( e.getSource( ) == isPalindrome ) { // isPalindrome pressed. String enteredText = text.getText( ); if( enteredText.length( ) > 0 ) { if( isPalindromic( enteredText ) ) { output.setText( enteredText + " is palindromic" ); } else { output.setText( enteredText + " is not palindromic" ); } else { // quit pressed. System.exit( 0 ); } PalindromeGUI / ActionListener instance Button instance isPalindrome quit listener 1: addActionListener( this ) 2: actionPerformed( ) Button instance Example: PalindromeGUI2.java 1128
29
Custom Painting in AWT Container Component paint( g : Graphics ) : void repaint( ) : void Panel MousePositionPanel > MouseListener Overrides paint( ) to print the location of the last mouse click 1129
30
Example: MouseListener Steps: Implements the MouseListener interface Adds an MouseListener Implements 5 methods: mousePressed mouseReleased mouseClicked mouseEntered mouseExited Calls repaint(): to update the position class MousePositionPanel extends Panel implements MouseListener { private int mouseX, mouseY; public MousePositionPanel( ) { mouseX = 100; mouseY = 100; addMouseListener( this ); } public void paint( Graphics g ) { g.drawString( "(" + mouseX + ", " + mouseY + ")", mouseX, mouseY ); } public void mousePressed( MouseEvent e ) { mouseX = e.getX( ); mouseY = e.getY( ); repaint( ); } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } } Example: MousePositionPanel.java 1130
31
No need to give inner classes names! public class PalindromeGUI3 extends Frame { private TextField text; private Button isPalindrome, quit; private Label output; public PalindromeGUI3( ) { … isPalindrome.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { String enteredText = text.getText( ); if( enteredText.length( ) > 0 ) if( isPalindromic( enteredText ) ) output.setText( enteredText + " is palindromic" ); else output.setText( enteredText + " is not palindromic" ); } } ); quit.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { System.exit( 0 ); } } ); … } PalindromeGUI instance Button instance isPalindrome quit listener actionPerformed( ) Button instance ActionListener instance Anonymous Inner Classes Note: don’t need to use the getSource() method have access to all instance variables of the enclosing class Example: PalindromeGUI3.java 1131
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.