Swing User Interface Components. In this class we will cover: Model-View-Controller Design Pattern Layout Management Text Input.

Slides:



Advertisements
Similar presentations
G5BUID - Java Swing Laying out components Manage realized components Determine size and position Each container has a layout manager (usually)
Advertisements

Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Graphical User Interfaces
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Corresponds with Chapter 12
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Graphical User Interface (GUI) Programming III. Lecture Objectives Exploring more GUI programming elements in Java Using labels in GUIs Using colors to.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Design Patterns and Graphical User Interfaces Horstmann ,
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Adding Graphics to a Frame Application Applets: Can generate drawings by overriding paint Frame: Do not draw directly on a frame. Draw graphics on a JPanel.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
CHAPTER:07 JAVA IDE PROGRAMMING-II Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
Copyright © Curt Hill More Widgets In Abstract Window Toolbox.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Layouts CSIS 3701: Advanced Object Oriented Programming.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
Chapter 7 A First Look at GUI Applications Layout Managers.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Swing JComponents.
“Form Ever Follows Function” Louis Henri Sullivan
Modern Programming Language Java
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Swing User Interface Components

In this class we will cover: Model-View-Controller Design Pattern Layout Management Text Input

Model-View-Controller Design Pattern To better understand Swing UI components, it is a good idea to review how Swing works at an architectural level. All Swing components (e.g. buttons, check boxes, text fields, etc) have three basic characteristics: –Its contents such as the state of a button (pushed in or not), the text in a text field –Its visual appearance color, size, etc. –Its behavior reaction to events To implement these characteristics, Swing uses a well- known design pattern - the Model-View-Controller patter. –This pattern goes back to the principles of OO design - don’t make one object responsible for too much.

Model-View-Controller Design Pattern The MVC design pattern: –The model stores the contents –The view dsplays the contents –The controller handles user input The advantage of this pattern is that a model can have multiple views, each showing a different aspect of the full contents –For example, an html editor can offer two simultaneous views of the same contents. It can show the WYSIWYG view or the raw tag view depending on what the user wishes to see.

Model-View-Controller Design Pattern The controller handles the user input events such as mouse clicks and keystrokes. It then decides whether to translate these events into changes in the model or the view. –e.g. a keystroke in a text field causes the controller to call the “insert character” command in the model. The model then tells the view to update itself. –e.g. likewise, if the user presses a cursor, the controller tells the view to scroll. The model is never affected. Swing insulates the programmer from the MVC architecture with wrapper classes such as JButton or JTextField that store the model and the view.

Layout Management All components in a container are managed by a layout manager. FlowLayout manager –The default layout manager for a panel is the flow layout manager. –The flow layout manager lines the components horizontally until there is no more room and then starts another row. –You can choose how you want to arrange components in this row. The default is to center the components but you can align them to the left or right by specifying LEFT or RIGHT in the constructor: e.g. setLayout(new FlowLayout(FlowLayout.LEFT));

Layout Management BorderLayout manager –This is the default layout manager for the content pane. –It has 5 sections - North, South, East, West, and Center. –class MyPanel extends JPanel { setLayout(new BorderLayout()); … add (yellowButton, BorderLayout.SOUTH); } –The edge components are laid out first and the remaining available space is occupied by the center. –If you don’t specify NORTH, SOUTH, EAST, WEST, or CENTER, CENTER is assumed.

Layout Management Using Panels with BorderLayout –The BorderLayout is not very useful by itself in the content pane. –It should be used with panels that act as small containers. You can have several panels in the content pane. –Container contentPane = getContentPane(); JPanel panel = new JPanel(); panel.add(yellowButton); panel.add(blueButton); panel.add(redButton); contentPane.add(panel, BorderLayout.SOUTH); –All containers have a setLayout method to set the layout manager to something other than the default for the container.

Layout Management Grid Layout –arranges all components in rows and columns like a spreadsheet –cells are always the same size –example panel.setLayout(new GridLayout(5, 4)); –you can also specify the veritical and horizontal gaps between the components in pixels panel.setLayout(new GridLayout(5, 4, 3, 3)

Text Input Text fields –Use JTextField to accept one line of text –JPanel panel = new JPanel(); JTextField textField = new JTextField(“Defaul Input”, 20); panel.add(textField); –You can use the setText method to change the text later. textField.setText(“Hello”); –You can use the getText method to get the text from the field. Use the trim method to get rid of leading / trailing spaces. String text = textField.getText().trim()

Text Input You can use the DocumentListener to notify you when data has changed. textField.getDocument().addDocumentListener(listener); –When the text has been changed in a text field 1 of 3 methods will be called. void insertUdate (DocumentEvent e); void removeUpdate(DocumentEvent e); void changedUpdate(DocumentEvent e); Instead of listening to document events, you can also add an action event listener to a text field. Remember, though, the action listener is notified only when the user hits enter (not when they tab out of the field).

Text Input Password Fields For password fields, the characters that the user entered are not actually displayed. Instead, each typed character is represented by an echo character (usually an asterisk). Use the JPasswordField class to implement such a text field. JPasswordField password = new JPasswordField(“default input”,20); password.setEchoChar(*);

Text Input Formatted Input Fields Integer Input –Use the JFormattedTextField JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance()); –You can set the default value and the number of columns by using these methods: intField.setValue(new Integer(100)); intField.setColumns(6); –You can use the getalue method to read the value the user supplied. You need to cast the value to a Number object though. Number value = (Number)intField.getValue(); int v = value.intValue();

Text Input Behavior on Loss of Focus When the user types in a text field and then leaves the field by clicking on another component, the text field loses focus. When a formatted text field loses focus, the formatter looks at the text string that the user produced. If the formatter knows how to covert the text string to an object, the text is valid. You can use the isEditValid method to check if the current contents of the text field are valid.

Text Input Verifiers If a verifier is used, the moment a text field loses focus, the verifier is queried. If he verifier reports the contents to be invalid, the text field immediately regains focus. The user is forced to fix the contents before supplying other inputs. For example, if the formatter is checking for numerics and the user enters an alpha character, the verifier will force the user to enter only numerics before moving on.

Text Input Verifiers Here is an example of a verifier: class FormattedTextFieldVerifier extends InputVerifier { public boolean verify (JComponent component) { JFormattedTextField field = (JFormattedTextField)component; return field.isEditValid(); } } Note, the verifier class must extend the InputVerifier class and override the verify method.

Text Input Other Standard Formatters Besides the integer formatter, the JFormattedTextField supports several other formatters: –The NumberFormat class has these methods: getNumberInstance getCurrencyInstance getPercentInstance –The DateFormat class has these methods: getDateInstance getTimeInstance getDateTimeInstance

Text Input Other Standard Formatters The DefaultFormatter can format objects of any class that has a constructor with a string parameter and a matching toString method. –For example, the URL class has URL(String) constructor that can be used to build a URL object from a string. –So, you can use the DefaultFormatter to format URL objects. –This will force the user to enter in a valid URL string (e.g. must have http in it).

Text Input Other Standard Formatters The MaskFormatter is useful for fixed-size patterns that contain some constant and some variable characaters like ssn. –new MaskFormatter(“###-##-####”); Furthermore, you can restrict the characters that can be typed into the field by calling one of the methods: –setValidCharacters –setInvalidCharacters

Text Input Filters and Custom Formatters You can use document filters to prevent the user from entering certain characters automatically. See pg. 358 for the code to do this. In addition, you can create your own custom formatters. See pg. 362 for information on these.

Text Areas Use the JTextArea class to create a text area where users can enter any number of lines of text, using ENTER to separate them. JTextArea textArea = new JTextArea(8, 40); // 8 lines and 40 columns textArea.setLineWrap(true); // wrap long lines JScrollPane scrollPane = new JScrollPane(textArea); // add scroll bars contentPane.add(scrollPane); JTextArea only displays plain text. Use JEditorPane or JTextPane to display formated text such as HTML or RTF.

Labels Labels are components that hold text. They have no decorations (e.g. no boundries) and they do not react to user input. You can use a label to identify components. JLabel label = new JLabel(“Text”, JLabel.LEFT);

Selecting and Editing Text The text field and the text area classes have methods that can check highlighted text. –use the getSelectionStart, getSelectionEnd, and the getSelectedText methods The JTextArea has a number of methods used to modify the contents of a text area. –You can append text, insert text, and replace text. See pg. 376 for more info.

Putting it all together See www2.bc.edu/~bernier/MC697/LectureNotes/TestTextFor mat.java www2.bc.edu/~bernier/MC697/LectureNotes/TestTextFor mat.java