Download presentation
Presentation is loading. Please wait.
Published byEstifanos Tilahun Mihret Modified over 5 years ago
1
Advanced Programming Estifanos T. (MSc in Computer Networking)
2
CHAPTER ONE AWT and Swing Estifanos T. (MSc in Computer Networking)
3
Objectives 3 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) To explain the concepts of AWT and Swing To describe the Frame, Label, Button, TextField and ComboBox To discuss JFrame, JLabel, JButton, JTextField, and JComboBox To explore Event Handling, Sources and Listeners
4
Concepts of AWT and Swing AWT is stands for Abstract Windowing Toolkit The AWT is roughly broken into three categories Components Layout Managers Graphics Many AWT components have been replaced by Swing components It is generally not considered a good idea to mix Swing components and AWT components. Choose to use one or the other 4 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
5
AWT Class Hierarchy 5 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Panel Button Checkbox Choice Label List Component ContainerFrameWindow TextAreaTextFieldTextComponent Note: There are more classes, however, these are what are covered in this chapter
6
Component 6 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Component is the superclass of most of the displayable classes defined within the AWT. Note: it is abstract MenuComponent is another class which is similar to Component except it is the superclass for all GUI items which can be displayed within a drop-down menu The Component class defines data and methods which are relevant to all Components setBounds setEnabled setSize setForeground-- colour setLocation setBackground -- colour setFont setVisible
7
Container 7 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Container is a subclass of Component. (i.e.. All containers are themselves, Components) Containers contain components For a component to be placed on the screen, it must be placed within a Container The Container class defined all the data and methods necessary for managing groups of Components add remove getComponent removeAll getMaximumSize getPreferredSize getMinimumSize
8
Windows and Frames 8 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) The Window class defines a top-level Window with no Borders or Menu bar Usually used for application splash screens Frame defines a top-level Window with Borders and a Menu Bar Frames are more commonly used than Windows Once defined, a Frame is a Container which can contain Components Frame aFrame = new Frame (Hello World); aFrame.setSize(100,100); aFrame.setLocation(10,10); aFrame.setVisible(true);
9
Panels 9 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) When writing a GUI application, the GUI portion can become quite complex To manage the complexity, GUIs are broken down into groups of components. Each group generally provides a unit of functionality A Panel is a rectangular Container whose sole purpose is to hold and manage components within a GUI Panel aPanel = new Panel(); aPanel.add(new Button("Ok")); aPanel.add(new Button("Cancel")); Frame aFrame = new Frame("Button Test"); aFrame.setSize(100,100); aFrame.setLocation(10,10); aFrame.add(aPanel);
10
Buttons 10 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class represents a push-button which displays some specified text When a button is pressed, it notifies its Listeners To be a Listener for a button, an object must implement the ActionListener Interface Panel aPanel = new Panel(); Button okButton = new Button("Ok"); Button cancelButton = new Button("Cancel"); aPanel.add(okButton)); aPanel.add(cancelButton)); okButton.addActionListener(controller2); cancelButton.addActionListener(controller1);
11
Labels 11 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class is a Component which displays a single line of text Labels are read-only. That is, the user cannot click on a label to edit the text it displays Text can be aligned within the label Label aLabel = new Label("Enter password:"); aLabel.setAlignment(Label.RIGHT); aPanel.add(aLabel);
12
List 12 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class is a Component which displays a list of Strings The list is scrollable, if necessary Sometimes called Listbox in other languages Lists can be set up to allow single or multiple selections The list will return an array indicating which Strings are selected List aList = new List(); aList.add("Calgary"); aList.add("Edmonton"); aList.add("Regina"); aList.add("Vancouver"); aList.setMultipleMode(true);
13
Checkbox 13 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class represents a GUI checkbox with a textual label The Checkbox maintains a boolean state indicating whether it is checked or not If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button Checkbox creamCheckbox = new CheckBox("Cream"); Checkbox sugarCheckbox = new CheckBox("Sugar"); [… ] if (creamCheckbox.getState()) { coffee.addCream(); }
14
Choice 14 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class represents a dropdown list of Strings Similar to a list in terms of functionality, but displayed differently Only one item from the list can be selected at one time and the currently selected element is displayed Choice aChoice = new Choice(); aChoice.add("Calgary"); aChoice.add("Edmonton"); aChoice.add("Alert Bay"); [… ] String selectedDestination= aChoice.getSelectedItem();
15
TextField 15 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class displays a single line of optionally editable text This class inherits several methods from TextComponent This is one of the most commonly used Components in the AWT TextField emailTextField = new TextField(); TextField passwordTextField = new TextField(); passwordTextField.setEchoChar("*"); […] String userEmail = emailTextField.getText(); String userPassword = passwordTextField.getText();
16
TextArea 16 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) This class displays multiple lines of optionally editable text This class inherits several methods from TextComponent TextArea also provides the methods: appendText(), insertText() and replaceText() // 5 rows, 80 columns TextArea fullAddressTextArea = new TextArea(5, 80); […] String userFullAddress= fullAddressTextArea.getText();
17
Layout Managers 17 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Since the Component class defines the setSize() and setLocation() methods, all Components can be sized and positioned with those methods Problem: the parameters provided to those methods are defined in terms of pixels. Pixel sizes may be different (depending on the platform) so the use of those methods tends to produce GUIs which will not display properly on all platforms Solution: Layout Managers. Layout managers are assigned to Containers. When a Component is added to a Container, its Layout Manager is consulted in order to determine the size and placement of the Component NOTE: If you use a Layout Manager, you can no longer change the size and location of a Component through the setSize and setLocation methods
18
Layout Managers 18 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) There are several different LayoutManagers, each of which sizes and positions its Components based on an algorithm: FlowLayout BorderLayout GridLayout For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the default LayoutManager is FlowLayout
19
Flow Layout 19 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) The algorithm used by the FlowLayout is to lay out Components like words on a page: Left to right, top to bottom It fits as many Components into a given row before moving to the next row Panel aPanel = new Panel(); aPanel.add(new Button("Ok")); aPanel.add(new Button("Add")); aPanel.add(new Button("Delete")); aPanel.add(new Button("Cancel"));
20
Border Layout 20 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) The BorderLayout Manager breaks the Container up into 5 regions (North, South, East, West, and Centre) When Components are added, their region is also specified: Frame aFrame = new Frame(); aFrame.add("North", new Button("Ok")); aFrame.add("South", new Button("Add")); aFrame.add("East", new Button("Delete")); aFrame.add("West", new Button("Cancel")); aFrame.add("Center", new Button("Recalculate"));
21
Border Layout 21 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) The regions of the BorderLayout are defined as shown on the above Centre NorthSouth WestEast
22
Grid Layout 22 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) The GridLayout class divides the region into a grid of equally sized rows and columns Components are added left-to-right, top-to-bottom The number of rows and columns is specified in the constructor for the LayoutManager Panel aPanel = new Panel(); GridLayout theLayout = new GridLayout(2,2); aPanel.setLayout(theLayout); aPanel.add(new Button("Ok")); aPanel.add(new Button("Add")); aPanel.add(new Button("Delete")); aPanel.add(new Button("Cancel"));
23
What If I Don’t Want a Layout Manager 23 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) LayoutManagers have proved to be difficult and frustrating to deal with The LayoutManager can be removed from a Container by invoking its setLayout method with a null parameter Panel aPanel = new Panel(); aPanel.setLayout(null);
24
Graphics 24 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) It is possible to draw lines and various shapes within a Panel under the AWT Each Component contains a Graphics object which defines a Graphics Context which can be obtained by a call to getGraphics() Common methods used in Graphics include: drawLine draw3DRect drawOval fillArc drawPolygon drawPolyLine drawRect drawRoundRect drawString fill3DRect
25
AWT Packages 25 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) java.awt Basic component functionality java.awt.accessibility Assistive technologies java.awt.color Colors and color spaces java.awt.datatransfer Clipboard and data transfer support java.awt.dnd Drag and drop java.awt.event Event classes and listeners java.awt.font 2D API font package java.awt.geom 2D API geometry package java.awt.im Input methods java.awt.image Fundamental image manipulation classes java.awt.peer Peer interfaces for component peers java.awt.print 2D API support for printing java.awt.swing Swing components
26
Swing 26 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Same concepts as AWT Doesn’t work in ancient Java implementations (Java 1.1 and earlier) Many more controls, and they are more flexible Some controls, but not all, are a lot more complicated Gives a choice of “look and feel” packages Much easier to build an attractive GUI import javax.swing.*;
27
Swing vs AWT 27 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Swing is bigger, slower, and more complicated But not as slow as it used to be Swing is more flexible and better looking Swing and AWT are incompatible--you can use either, but you can’t mix them Actually, you can, but it’s tricky and not worth doing Learning the AWT is a good start on learning Swing Many of the most common controls are just renamed AWT: import java.awt.*; AWT: Button b = new Button ("OK"); Swing: import javax.swing.*; Swing: JButton b = new JButton("OK");
28
Swing Components 28 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Containers Contain and manage other components Top Level/Internal Examples: JFrame (Top Level), JScrollPane, Jpanel Basic Controls Atomic components Used for showing output and/or getting some input Inherits Jcomponent Examples: JButton, JLabel, JTextArea, JTable, Jlist Usually every Swing class extends the corresponding AWT class For backward-compatibility reasons
29
Swing Components 29 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
30
Swing Components 30 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
31
Simple Swing Program 31 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) import javax.swing.*; import java.awt.BorderLayout; public class CoSc { public static void main(String[] args) { JFrame cosc= new JFrame(“Department of Computer Science"); // operation to do when the window is closed. cosc.setLayout(new BorderLayout()); cosc.add(new JLabel("I Love Computer Science Department"), BorderLayout.CENTER); cosc.pack(); cosc.setVisible(true); }}
32
Top Level Containers: JDialog 32 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) javax.swing.JDialog: More simple and limited than frames Typically used for showing a short message on the screen Also has a border and a title bar May have an owner If the owner is invisible the dialog will also be invisible Use the static method of JOptionPane to show standard dialog boxes: JOptionPane.showMessageDialog(null, "4+2=6");
33
Top Level Containers: JFileChooser 33 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) javax.swing.JFileChooser: Allows the user to choose a file Supports “open” and “save”: showOpenDialog(), showSaveDialog() JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());
34
Top Level Containers: JFrame 34 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) javax.swing.JFrame: Top-level window with a title and a border Usually used as a program's main window
35
Internal Containers 35 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Not Top level containers Can contain other non-top level components Examples: JScrollPane: Provides a scrollable view of its components JSplitPane: Separates two components JTabbedPane: User chooses which component to see
36
Containers - Layout 36 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Each container has a layout manager Determines the size, location of contained widgets Setting the current layout of a container: void setLayout(LayoutManager lm) LayoutManager implementing classes: BorderLayout BoxLayout FlowLayout GridLayout
37
Containers - Layout 37 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
38
Input 38 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) So we now know how to present widgets on the screen A program also needs to react to the user's actions Examples: When the user presses a button we want to save a file When the user closes the program we want to ask “are you sure?” ... Swing mechanism: Events and Listeners
39
Events, Listeners 39 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Swing defines all sorts of Listener interfaces E.g.: ActionListener, MouseMotionListener, WindowListener,... public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); } public interface MouseMotionListener extends EventListener { public void mouseDragged(MouseEvent e); public void mouseMoved(MouseEvent e); } There are default (empty) implementations for many of the listeners E.g.: MouseMotionAdapter, WindowAdapter
40
Events, Listeners 40 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) A listener is an object that implements a listener interface If we need to react to an event (on a certain widget) we register a listener object with that widget E.g.: addActionListener() registers an action listener with its receiver: JButton button = new JButton(); ActionListener listener =...; button.addActionListener(listener); When an event occurs, all registered listeners are notified The appropriate listener method (e.g: actionPerformed()) is invoked An object describing the event is passed as a parameter
41
Event Handling Demo: GUI 41 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
42
Event Handling Demo: Code 42 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Events implements ActionListener { public Events() { JFrame frame = new JFrame("Events"); frame.setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(this); frame.add(b); frame.pack(); frame.setVisible(true); }
43
Event Handling Demo: Code 43 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); }
44
Swing’s JTable 44 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Each JTable has a TableModel object that holds the data shown by the table DefaultTableModel is a default implementation of TableModel By default it makes all the cells editable We can customize its behavior by subclassing Or we can implement TableModel from scratch TableModelListener - a listener interface Notified of changes in the model Use TableModel.addTableModelListener() to register a listener object
45
Contacts Book Example Overview 45 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking) Each contact has a name and a list of attributes Each attribute has a name and a value Operations: Add contact Contact name is immutable Add attributes Attribute is identified by it’s name, the attribute name is immutable, it’s value can be changed Classes: Contact: represents a contact and maintains list of attributes Contact.Attribute: Inner class that represents contact attribute ContactTableModel: model class for the table data Doesn’t allow to modify attribute names ContactBook: represents the contact book widget
46
Contacts Book Example Overview 46 Lecture 1: AWT and Swing 9/9/2019 Estifanos T. (MSc in Computer Networking)
47
End Of Chapter One
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.