1 / 76

CS 112 Introduction to Programming

CS 112 Introduction to Programming. Swing/Android GUI Programming Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu. Admin. Merge tournament and project demo Change Friday ’ s class -> a Hack Day

Download Presentation

CS 112 Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 112 Introduction to Programming Swing/Android GUI Programming Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

  2. Admin • Merge tournament and project demo • Change Friday’s class -> a Hack Day • A deck of slides on Strong/Weak AI • Apr. 30: 11:30-1 pm • required attendance: a fair trade

  3. Recap: Servlet and JSP • A basic concept of Web programming is that the unit of user interaction is Web page • A form on a page defines the program to be invoked and the set of parameters to be collected and sent to the specified program; the program returns a Web page • Servlet is a programming framework for designing Web backend • One customizes the behavior of Servlet by overriding methods doGet/doPost • JSP provides a syntax sugar for Servlet programming • You may checkout PHP

  4. Outline • Admin and recap • GUI design overview

  5. GUI Overview • Standard Java provides a GUI framework (called Swing) to support the development of GUI applications • Android adapts the standard GUI framework to support the development of Android applications • GUI systems can be diverse, complex • The ease of developing GUI applications using a GUI framework is the key to its success • We will see both Swing and Android, to illustrate the common and evolving design decisions.

  6. GUI Programming Framework Goals • Discussion: Common issues in designing a GUI framework?

  7. GUI Programming Framework Goals • Display: how to create and layout GUI components • User interaction: how to specify user action on a GUI component

  8. Outline • Admin and recap • Interface • Examples: GUI design • Overview • Display

  9. Design for Display • Problem: Re-usability • Basic idea • Design a large number of standard GUI display/view components

  10. Swing: JButton, JLabel The most common component—a button is a clickable onscreen region that the user interacts with to perform a single command A text label is simply a string of textdisplayed on screen in a graphical program. Labels often give infor-mation or describe other components • public JButton(String text)public JLabel(String text)Creates a new button / label with the given string as its text. • public String getText()Returns the text showing on the button / label. • public void setText(String text)Sets button / label's text to be the given string.

  11. Swing: JTextField, JTextArea A text field is like a label, except that the textin it can be edited and modified by the user.Text fields are commonly used for user input,where the user types information in the field and the program reads it A text area is a multi-line text field • public JTextField(int columns) • public JTextArea(int lines, int columns)Creates a new text field the given number of columns (letters) wide. • public String getText()Returns the text currently in the field. • public void setText(String text)Sets field's text to be the given string.

  12. Swing: JFileChooser A special dialog box that allows the user to selectone or more files/folders • public JFileChooser() • public JFileChooser(String currentDir) • public int showOpenDialog(Component parent) • public int showSaveDialog(Component parent) • public File getSelectedFile() • public static int APPROVE_OPTION, CANCEL_OPTIONPossible result values from showXxxDialog(..). JFileChooser chooser = new JFileChooser(); int result = chooser.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) this.saveData(chooser.getSelectedFile().getName());

  13. Swing: JColorChooser Another special dialog thatlets the user pick from apalette of colors • public JColorChooser() • public JColorChooser(Color initial) • public Color showDialog(Component parent, String title, Color initialColor) • returns null if user chose Cancel option

  14. Android

  15. Design for Display • Problem: • A GUI app often uses multiple components and a major work is to layout the components • Basic idea • Allow a GUI component to be a container: • One can add components to a container • A container has a layout manager to manage how components in it are arranged.

  16. Containers • container:An object that holds components; it also governs their positions, sizes, and resizing behavior. • Containers have the following public methods: • public void add(Component comp)public void add(Component comp, Object info)Adds a component to the container, possibly giving extra information about where to place it. • public void remove(Component comp)Removes the given component from the container. • public void setLayout(LayoutManager mgr)Uses the given layout manager to position the components in the container. • public void validate()You should call this if you change the contents of a container that is already on the screen, to make it re-do its layout.

  17. Standard Swing GUI Class Hierarchy (A Very Small Subset) Component Container Window JComponent Frame JPanel JAbstractButton JButton JToggleButton JFrame Typically used as top-level standalone container in Swing GUI app. Android is called Activity JCheckBox JRadioBox

  18. JFrame A frame is a graphical window that can be used to hold other components • public JFrame()public JFrame(String title)Creates a frame with an optional title. • public void setTitle(String text)Puts the given text in the frame’s title bar. • public void setDefaultCloseOperation(int op)Makes the frame perform the given action when it closes. Common value: JFrame.EXIT_ON_CLOSE • NOTE: Call setVisible(true) to make a frame appear on screen after creating it.

  19. JFrame Example • A simple program that creates and shows a JFrame: import java.awt.*; import javax.swing.*; public class SimpleFrame { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setForeground(Color.WHITE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(300, 120)); frame.setTitle("A frame"); frame.setVisible(true); } } • Graphical output:

  20. Design for Display • Problem: • How does a programmer specify where each component sits in the container, how big each component should be, and what the component should do if the window is resized/moved/maximized/etc? • Basic idea: • Layout managers, which define templates

  21. Layout managers • Here are several common Java layout managers:

  22. Preferred size • Swing component objects each have a certain size they would "like" to be--just large enough to fit their contents (text, icons, etc.) • This is called the preferred size of the component • Some types of layout managers (e.g. FlowLayout) choose to size the components inside them to the preferred size; others (e.g. BorderLayout, GridLayout) disregard the preferred size and use some other scheme Buttons at preferred size: Not preferred size:

  23. FlowLayout public FlowLayout() • treats container as a left-to-right, top-to-bottom "page" or "paragraph" • components are given their preferred size both horizontally and vertically • components are positioned in order added • if too long, components wrap around to next line Container panel = new JPanel(new FlowLayout()); panel.add(new JButton("Button 1"));

  24. FlowLayout example import java.awt.*; import javax.swing.*; public class FlowLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(320, 75)); frame.setTitle("Flow layout"); frame.setLayout(new FlowLayout()); frame.add(new JLabel("Type your ZIP Code: ")); frame.add(new JTextField(5)); frame.add(new JButton("Submit")); frame.setVisible(true); } }

  25. GridLayout public GridLayout(int rows, int columns) • treats container as a grid of equally-sized rows and columns • components are given equal horizontal / vertical size, disregarding preferred size

  26. GridLayout example import java.awt.*; import javax.swing.*; public class GridLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(300, 120)); frame.setTitle("The grid"); // 2 rows, 3 columns frame.setLayout(new GridLayout(2, 3)); for (int i = 1; i <= 6; i++) { JButton button = new JButton(); button.setText("Button " + i); frame.add(button); } frame.setVisible(true); } }

  27. BorderLayout public BorderLayout() • divides container into five regions: NORTH, SOUTH, WEST, EAST, CENTER • NORTH and SOUTH regions expand to fill region horizontally, and use preferred size vertically • WEST and EAST regions expand to fill region vertically, and use preferred size horizontally • CENTER uses all space not occupied by others Container panel = new JPanel(new BorderLayout()); panel.add(new JButton("Button 1 (NORTH)", BorderLayout.NORTH);

  28. BorderLayout example import java.awt.*; import javax.swing.*; public class BorderLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(210, 200)); frame.setTitle("Run for the border"); frame.setLayout(new BorderLayout()); frame.add(new JButton("north"), BorderLayout.NORTH); frame.add(new JButton("south"), BorderLayout.SOUTH); frame.add(new JButton("west"), BorderLayout.WEST); frame.add(new JButton("east"), BorderLayout.EAST); frame.add(new JButton("center"), BorderLayout.CENTER); frame.setVisible(true); } }

  29. BoxLayout Box.createHorizontalBox() Box.createVerticalBox() • aligns components in container in a single row or column • components use preferred sizes and align based on their preferred alignment • preferred way to construct a container with box layout:Box.createHorizontalBox(); or Box.createVerticalBox();

  30. Complex layouts • Can you create a layout like this, using one preceding layout manager?

  31. Solution: composite layout • Create container within container • Each container has a different layout, and by combining the layouts, more complex / powerful layout can be achieved • In Swing, we typically use JPanel as container to form container hierarchy: • public JPanel()Constructs a panel with a default flow layout. • public JPanel(LayoutManager mgr)Constructs a panel that uses the given layout manager.

  32. GUI App Key Entities DisplayComposite Display Composite Display Display Display DisplayComposite Display Display

  33. Composite layout example import java.awt.*; import javax.swing.*; public class TelephonePad { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(250, 200)); frame.setTitle("Telephone"); frame.setLayout(new BorderLayout()); JPanel centerPanel = new JPanel(new GridLayout(4, 3)); for (int i = 1; i <= 9; i++) { centerPanel.add(new JButton("" + i)); } centerPanel.add(new JButton("*")); centerPanel.add(new JButton("0")); centerPanel.add(new JButton("#")); frame.add(centerPanel, BorderLayout.CENTER); JPanel southPanel = new JPanel(new FlowLayout()); southPanel.add(new JLabel("Number to dial: ")); southPanel.add(new JTextField(10)); frame.add(southPanel, BorderLayout.SOUTH); frame.setVisible(true); } }

  34. Design for Display • Problem: extensibility • Allow flexible extension (i.e., creation of new types of display components) • Basic idea • Allow app to override draw method to generate new visual display

  35. Class Hierarchy (A Very Small Subset) To create a new visual component, extends JComponent and overrides paintComponent() JComponent paintComponent() JPanel JAbstractButton JLabel JTextComponent JButton JToggleButton JTextArea JTextField JCheckBox JRadioBox JPasswordField

  36. Display Extension Example • FaceViewer.java, FaceComponent.java • Extends JButton to customize its look

  37. Android Simplification • Restructure layout managers, such as: • You may want to check out more dynamic layout such as ListView http://developer.android.com/guide/topics/ui/declaring-layout.html

  38. Android: Allow the layout specification to be declarative

  39. Example: LetterGame

  40. Outline • Admin and recap • Interface • Examples: GUI design • Overview • Display • User interaction

  41. User Interaction • GUI framework identifies the component (view) over which a user-interaction event happens Key Mouse MouseMotion Touch component

  42. Design Decision: Partition Event Types • Since many types of events can happen and a component may not be interested in all of them, classify events into different categories so that a component can select the types (categories) of events to which it wants to respond. Key Mouse MouseMotion Touch component

  43. Java GUI Event Handling Steps • If a component wants to respond to a given category of events, the component should have a delegate (listener object) for that category of events • When an event of that category happened, the GUI manager will invoke the method of the listener object • the listener provides callback • To make sure that an installed listener object can handle a category of events, it should implement the listener interface for that category of event

  44. MouseListener Interface • Methods in the MouseListener interface: void mousePressed (MouseEvent event); called when the mouse button is pressed down. void mouseReleased (MouseEvent event); called when the mouse button is released. void mouseClicked (MouseEvent event); called if the mouse button is pressed & released at the same location. void mouseEntered (MouseEvent event); called when the mouse pointer passes into a component void mouseExited (MouseEvent event); called when the mouse pointer passes out of a component

  45. MouseMotionListener • Methods in the MouseMotionListener interface: void mouseDragged (MouseEvent event); called when the mouse button is pressed on a component and then dragged void mouseMoved (MouseEvent event); called when the mouse button has been moved on a component (with no buttons down)

  46. Installing a Listener • If an object implements a listener interface, it can be installed as the listener object for the type of event public class RubberLinesPanel implements MouseListener, MouseMotionListener { public RuberLinesPanel() { addMouseListener( this ); addMouseMotionListener( this ); … } public void mousePressed(MouseEvent e) {…} // all methods defined in interfaces }

  47. Event Listener This listener object waits for and responds to an event Events and Listeners Event source

  48. Event Handler DisplayComposite Display Composite Display Display Display DisplayComposite Event Handler Event Handler Display Display

  49. Example Swing GUI App: RubberBand

  50. Event Preprocessing • A component can define logic (think of a method) to map some raw events to more component-meaningful (semantic) events • E.g., allows a button component to map a mouse click, key press or touch to a "meaningful” event such as "button pressed“ • Such events are called ActionEvent in Swing Action Mouse MouseMotion Key component

More Related