Lecture 16 More GUI programming

Slides:



Advertisements
Similar presentations
Graphical User Interfaces
Advertisements

Java Software Development Paradigm Lecture # 12. Basics of GUI.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
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.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Consolidation. Code making (i.e. making ciphers) is undertaken by a cryptographer whereas cryptanalysts try to break ciphers in order to gain intelligence.
MSc Workshop - © S. Kamin, U.Reddy Lect 5 – GUI Prog - 1 Lecture 5 – GUI Programming r Inner classes  this and super r Layout r Reading: m.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
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.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
CS Lecture 01 Frames and Components and events Lynda Thomas
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
For (int i = 1; i
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Review_6 AWT, Swing, ActionListener, and Graphics.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Dept. of CSIE, National University of Tainan 10/21/2012 Working with Swing.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Lecture 15 Basic GUI programming
GUIs and Events Rick Mercer.
Swing JComponents.
A First Look at GUI Applications
Java GUI.
CHAPTER 7 & 8 REVIEW QUESTIONS
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
PC02 Consolidation %WITTY_QUOTE%. PC02 Consolidation %WITTY_QUOTE%
Steps to Creating a GUI Interface
Advanced Programming in Java
CiS 260: App Dev I Chapter 6: GUI and OOD.
Graphical User Interface
Presentation transcript:

Lecture 16 More GUI programming D&D 12 Date

Goals By the end of this lesson, you should: Be able to write Java applications with JTextField, JList, JCheckBox and JRadioButton components Be able to implement a ButtonGroup Be able to query the status of such checkboxes and radio buttons

The application The application Startup Imports Overview Constructor Event handling Summary

The application JFrame subclass: ListOWords JLabel JButton JTextField Startup Imports Overview Constructor Event handling Summary JFrame subclass: ListOWords JLabel JButton JTextField JCheckBox ButtonGroup JRadioButton JList JScrollPane

Application startup The application Startup Imports Overview Constructor Event handling Summary import javax.swing.SwingUtilities; public class RunListOWords implements Runnable { public void run() { ListOWords l = new ListOWords(); } public static void main(String[] args) { SwingUtilities.invokeLater(new RunListOWords()); This is again the proper way of starting our Swing application to ensure it runs in the event dispatch thread.

Imports in ListOWords The application Startup Imports Overview Constructor Event handling Summary import java.awt.FlowLayout; // Controls general layout on JFrame import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; // A Font (for those at the back) import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.ListSelectionModel; // for your homework import javax.swing.JButton; import javax.swing.JList; import javax.swing.ListModel; import javax.swing.DefaultListModel; import javax.swing.JScrollPane; // A scrollable pane for lists etc. import javax.swing.JCheckBox; import javax.swing.JPanel; // A panel for our radio buttons import java.awt.GridBagLayout; // Layout for our radio buttons import java.awt.GridBagConstraints; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; // groups radio buttons We need all of these imports in ListOWords.java so the Java compiler can resolve the various JComponents and AWT classes.

The fields in ListOWords The application Startup Imports Overview Constructor Event handling Summary public class ListOWords extends JFrame implements ActionListener { private final JLabel label; private final JButton button; private final JTextField textField; private final JList<String> wordList; private final JCheckBox checkBoxReverseString; private final JPanel radioButtonPanel; private final ButtonGroup radioButtons; private final JRadioButton radioButtonNormalCase; private final JRadioButton radioButtonUpperCase; private final JRadioButton radioButtonLowerCase; … The fields all correspond to the components we’ve identified on slide 4. The rest of the class consists of two methods: The constructor ListOWords(). It configures the JFrame and the components, and adds the components to the frame. The actionPerformed() method implements the ActionListener interface. Here, it handles the ActionEvent that the Add button dispatches.

The constructor The constructor ListOWords() sets up more or less the whole GUI. This is very common in GUI applications. The example here shows that this can result in quite a large piece of code with little structure, even for a small application like this. On the following slides, we will go through the constructor in “thematic” steps. The application Startup Imports Overview Constructor Event handling Summary

ListOWords() (part 1) The application Startup Imports Overview Constructor Event handling Summary public ListOWords() { super("Listing words in all sorts of ways"); setLayout(new FlowLayout()); setSize(300,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Font font = new Font("Sans-serif", Font.PLAIN, 20); label = new JLabel("New word to add"); label.setFont(font); add(label); textField = new JTextField(10); textField.setFont(font); add(textField); … Note: Configuration of the JFrame (layout, size, close behaviour) doesn’t have to happen in the class that starts the frame: Here, we have the ListOWords frame configure itself! FlowLayout arranges the components in the order in which they are added. The Font object here sets a font larger than default (so those of you in the cheap seats at the back can see it) We use that font in the JLabel and JTextField, among others.

ListOWords() (part 2) The application Startup Imports Overview Constructor Event handling Summary button = new JButton("Add"); button.addActionListener(this); button.setFont(font); add(button); checkBoxReverseString = new JCheckBox("Reverse string"); add(checkBoxReverseString); … The JButton configuration is the same as in our “Hello World” application. Again, we implement the ActionListener interface in the class so just pass this. The JCheckBox takes its label from the constructor parameter Note: The checkbox doesn’t use the Font object (sorry if you are in the cheap seats at the back). This is to give you an idea as to what default font size is, in comparison.

ListOWords() (part 3) These lines get us ready for the radio buttons The application Startup Imports Overview Constructor Event handling Summary radioButtonPanel = new JPanel(); radioButtonPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = GridBagConstraints.RELATIVE; c.anchor = GridBagConstraints.WEST; radioButtons = new ButtonGroup(); … These lines get us ready for the radio buttons A JPanel with a constrained GridBagLayout lets us arrange the buttons in a neat column. Each button will be positioned with 0 offset within the panel, left-aligned (WEST), with each button positioned vertically RELATIVE to the parent component (the JPanel) or its predecessor button. We also use a ButtonGroup. This data structure from AWT will ensure that only one of the buttons in the ButtonGroup can be checked at any one time. Next: The radio buttons

ListOWords() (part 4) The application Startup Imports Overview Constructor Event handling Summary radioButtonNormalCase = new JRadioButton("Leave case as is"); radioButtonNormalCase.setFont(font); radioButtonNormalCase.setSelected(true); radioButtons.add(radioButtonNormalCase); radioButtonPanel.add(radioButtonNormalCase, c); radioButtonUpperCase = new JRadioButton("All upper case"); radioButtonUpperCase.setFont(font); radioButtons.add(radioButtonUpperCase); radioButtonPanel.add(radioButtonUpperCase, c); radioButtonLowerCase = new JRadioButton("All lower case"); radioButtonLowerCase.setFont(font); radioButtons.add(radioButtonLowerCase); radioButtonPanel.add(radioButtonLowerCase, c); add(radioButtonPanel); … Note we set the first of the buttons as being selected. We then add the buttons both to the ButtonGroup and to the JPanel. Finally, we add the panel to the JFrame

ListOWords() (part 6) The application Startup Imports Overview Constructor Event handling Summary wordList = new JList<String>(new DefaultListModel<String>()); wordList.setFont(font); wordList.setVisibleRowCount(25); wordList.setFixedCellHeight(25); wordList.setFixedCellWidth(280); add(new JScrollPane(wordList)); setVisible(true); The DefaultListModel tells the JList how to implement the list internally, in this case as a Vector (a data structure similar to an ArrayList) The visible row count gives us the number of elements on the list that are visible without scrolling Packaging the list in a JScrollPane lets us scroll Cell height/width are the height and width of each individual element cell Play with these values to see what happens!

actionPerformed() The application Startup Imports Overview Constructor Event handling Summary public void actionPerformed(ActionEvent event) { String newWord = textField.getText(); if (checkBoxReverseString.isSelected()) { String reverseWord = ""; for (int i = newWord.length() - 1; i >= 0; i--) { reverseWord += newWord.charAt(i); } newWord = reverseWord; if (radioButtonUpperCase.isSelected()) { newWord = newWord.toUpperCase(); if (radioButtonLowerCase.isSelected()) { newWord = newWord.toLowerCase(); ((DefaultListModel)(wordList.getModel())).addElement(newWord); We check whether the checkbox is checked and reverse the string from the text field if required. We then check which radio button is checked and compute the upper/lowercase version as applicable. We then add the new word to the list…

actionPerformed() The application Startup Imports Overview Constructor Event handling Summary ((DefaultListModel)(wordList.getModel())).addElement(newWord); This looks a bit complex, right? Our problem here is that there is no uniform way to add elements to a JList. The methods for adding to a JList are defined in its list model. The list model is an interface, which is not implemented by the JList class, but by the underlying data structure that implements the list (in our case, the vector). So what we need to do here is: Get a reference to the underlying data structure with wordList.getModel(). This returns an object that implements a ListModel interface. Unfortunately, addElement() is not a method of ListModel. However, we know that the object returned is actually an instance of the DefaultListModel class, which has an addElement() method. So we typecast the ListModel return value to a DefaultListModel, and call addElement() on this reference.

What do we know The application Startup Imports Overview Constructor Event handling Summary We can configure the size and behavior of a JFrame subclass in its constructor. Using a Font object with setFont() allows us to change the font type and size on components. We can read the text in a JTextField with its getText() method. Radio buttons are typically grouped so only one of the buttons in the group can be checked. Checkboxes and radio buttons’ check states can be queried with the isSelected() method. The underlying storage in a JList is controlled by a data model. If we want a JList to scroll, we can package it in a JScrollPane Sometimes, we need type casting!

Resources & Homework The application Startup Imports Overview Constructor Event handling Summary D&D Chapter 12 https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html https://docs.oracle.com/javase/tutorial/uiswing/components/button.html https://docs.oracle.com/javase/tutorial/uiswing/components/list.html https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html Homework: Refactor (rewrite) the constructor of the ListOWords class such that it uses a series of private methods to set up the different parts of the GUI.

Next Lecture Even more GUI programming (Chapter 12)