Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.

Slides:



Advertisements
Similar presentations
Graphical User Interfaces (Part IV)
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Graphical User Interfaces, 2D Graphics & Game Programming.
Corresponds with Chapter 12
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
Inheritance Review CSC 171 FALL 2004 LECTURE 19. READING Read Horstmann, Chapter 11 Look at Chapter 12 – Will not be on MT or Final – One lab Begin Reading.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
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.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
GUI Programming using NetBeans. What is a GUI ? GUI – Graphical User Interface The (visual) interface between humans and computers Ranging from command.
Advanced Java and Android Programming Day 1: Introduction to GUI Programming Intro to GUI Programming1.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
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.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
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.
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.
1 Why layout managers Can we perform layout without them? –Yes. A container’s layout property can be set to null. Absolute positioning: specify size and.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
SWING. AbstractButton Swing Buttons are subclasses of the AbstractButton class, which extends JComponent. Abstract class javax.swing.AbstractButton AbstractButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
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.
CSE 501N Fall ‘09 18: Java GUI (Swing) 10 November 2009 Nick Leidenfrost.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
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.
Computer Science 209 GUIs Model/View/Controller Layouts.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-3 ( Book Chapter 14) GUI and Event-Driven Programming.
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.
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.
1 Lecture 8: User Interface Components with Swing.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Frame Windows Application program, not applet Construct and show frame JFrame frame = new JFrame(); *** frame.show(); *** Set default close operation..
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Chapter 7 A First Look at GUI Applications Layout Managers.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Modern Programming Language Java
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Timer class and inner classes
Creating Graphical User Interfaces
Graphical User Interface
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components as instance fields Initialize them in the constructor of your subclass If initialization code gets complex, simply add some helper methods

Example (files on website): Colors.java - simple GUI Colors2.java - same application written as JFrame class Colors3.java - helper methods added Try running ColorApp --- notice that this main program provides 3 Color button frames Vapp3.java - GUI w/ three panels written as JFrame class

Layout Management Up to now, we have had limited control over layout of components Each container uses a layout manager to direct the arrangement of its components All layout managers implement the LayoutManager interface (so they are of type LayoutManager) A container type class (JPanel, etc) provides a setLayout(LayoutManager), which changes the layout of that container object

Flow Layout The FlowJPanel uses the FlowLayoutManager by default. The flow layout manager lines the components horizontally until there is no more room and then starts a new row of components. When the user resizes the container, the layout manager automatically reflows the components to fill the available space. By default, components are centered in a row, but a left or right alignment can be set when constructing a flow layout manager. Continued…

Flow Layout continued FlowLayout Constructors FlowLayout (alignment) * alignment can be specified by a static FlowLayout field For example: panel.setLayout(new FlowLayout(FlowLayout.LEFT)); FlowLayout (alignment, int horizontalgap, int verticalgap) * gaps indicate # of pixels between components For example: panel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10)

Border Layout Border layout groups container into five areas: center, north, west, south and east Components Expand to Fill Space in the Border Layout

Border Layout Default layout manager for a Jframe (technically, the frame's content pane) Border layout lets you choose where to add a component by specifing the position like this (center is default): Expands each component to fill the entire allotted area Typically a panel is placed inside each area, to control the Layout for those components. The edge components are laid out first, with the remaining space occupied by the center. Resizing changes the center size, not the edge. panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH);

Grid Layout Arranges components in a grid with a fixed number of rows and columns Resizes each component so that they all have same size Expands each component to fill the entire allotted area Add the components, row by row, left to right: JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4);...

Grid Layout Figure 2: The Grid Layout

Choices Radio buttons Check boxes Combo boxes A Combo Box, Check Box, and Radio Buttons

Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive This is achieved by placing all associated buttons in a ButtonGroup object. The ButtonGroup turns 1 button off when the next one is turned on sButton = new JRadioButton("Small"); mButton = new JRadioButton("Medium"); lButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(sbutton); group.add(mbutton); group.add(lbutton);

Radio Buttons continued The ButtonGroup is a logical component, NOT a visual component. (You don’t place it into a panel) It is good practice to initialize one of the buttons to ON: sButton.setSelected(true); The buttons still need to be placed into a panel individually. panel.add(sButton); panel.add(mButton); panel.add(lButton);

Radio Buttons continued Your code can tell if a RadioButton is selected if (sButton.isSelected())... One usually wants to check which button is selected WHEN THE USER HAS clicked on ONE!! An ActionEvent is created when the user clicks on one of the buttons.. so this code is in an ActionListener !!

// Frame which allows the user to select it’s background color import javax.swing.*; import java.awt.event.*; import java.awt.Color; import java.awt.BorderLayout; public class RadDemo extends JFrame { public RadDemo(){ createpanel(); //set up panel pack(); }

public void createpanel() { //set up button and put in panel final JRadioButton redbtn = new JRadioButton("RED"); final JRadioButton bluebtn = new JRadioButton("BLUE"); final JRadioButton greenbtn = new JRadioButton("GREEN"); ButtonGroup grp = new ButtonGroup(); grp.add(redbtn); grp.add(bluebtn); grp.add(greenbtn); final JPanel btnpanel = new JPanel(); //put on panel btnpanel.add(redbtn); btnpanel.add(bluebtn); btnpanel.add(greenbtn);

redbtn.setSelected(true); //default button/color is red btnpanel.setBackground(Color.RED); class BtnListen implements ActionListener{ //define listener class public void actionPerformed (ActionEvent e) { if (redbtn.isSelected() ) btnpanel.setBackground(Color.RED); else if (bluebtn.isSelected() ) btnpanel.setBackground(Color.BLUE); else btnpanel.setBackground(Color.GREEN); } BtnListen blisten = new BtnListen(); //create and register listener object redbtn.addActionListener(blisten); bluebtn.addActionListener(blisten); greenbtn.addActionListener(blisten); getContentPane().add(btnpanel, BorderLayout.CENTER); //put on frame }

// main to create and show frame public class ColorPanel{ public static void main (String [] args) { //create and test one of these frames JFrame newframe = new RadDemo(); newframe.show(); }

Check Boxes Similar to radio button, BUT not usually mutually exclusive JCheckBox it = new JCheckBox("Italic"); JCheckBox bld = new JCheckBox(“Bold”); No need for button group --- if you put them in a ButtonGroup they will be mutually exclusive!! in Action listener …….. If (bld.isSelected() )...

Combo Boxes Combination of selection and text field Create JComboBox object, then ‘add’ the items JComboBox faceName = new JComboBox(); faceName.addItem("Serif"); faceName.addItem("SansSerif");... (Any object type can be added to ComboBox --toString determines what is displayed!!

Combo Boxes To initialize the ComboBox selection: facename.setSelectedItem(“Italics”); To get user selection: sel= (String)faceName.getSelectedItem(); if (sel.equals(“Bold”)) ……………….. Note: Cast needed because return type is Object !! An ActionEvent is created by a ComboBox if the user makes a choice!! So you need to create an ActionListener class and install it on ComboBox object.

Combo Box items are ‘indexed’.. Values stored in a ComboBOx are internally ‘indexed’ beginning at 0. Can work with the objects using their indices as well Another way to initialize the ComboBox selection: facename.setSelectedIndex(0); Accordingly, can get user selection: int ind = faceName.getSelectedIndex();

//method returns a panel with a combo box on it public JPanel makebottom() { final JTextField outbox = new JTextField(" $15.00", 10); //set up combo box and add a listener final JComboBox cbox = new JComboBox(); cbox.addItem("Large Price"); cbox.addItem("Medium Price"); cbox.addItem("Small Price"); cbox.setSelectedItem("Large Price");

//method continues //set up listener class BoxListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if (cbox.getSelectedItem().equals("Large Price")) outbox.setText("$15.00"); else if (cbox.getSelectedItem().equals("Medium Price")) outbox.setText("$10.00"); else outbox.setText("$8.00"); } BoxListener clisten = new BoxListener(); cbox.addActionListener(clisten); JPanel temp = new JPanel(); //set up panel temp.setBackground(Color.blue); temp.add(cbox); temp.add(outbox); return temp; }

JPanel temp = new JPanel(); //set up panel temp.setBackground(Color.blue); temp.add(cbox); temp.add(outbox); return temp; }

Text Areas Figure 8: The TextAreaViewer Application

Text Areas Use a JTextArea to show multiple lines of text You can specify the number of rows and columns: setText : to set the text of a text field or text area append : to add text to the end of a text area final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); Continued…

Text Areas Use newline characters to separate lines: To use for display purposes only: textArea.append(account.getBalance() + "\n"); textArea.setEditable(false); // program can call setText and append to change it

Text Areas To add scroll bars to a text area: JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);

Where as a Combo box lets the users choose from a discrete set of values, a slider offers a choice of a value from within a range. Sliders

Constructors JSlider (int min, int max, int initVal) JSlider( int orientation, int min, int max) JSlider (int min, int max) Visuals: setMajorTickSpacing(int n) setMinorTIckSpacing((int n) setPaintTicks(boolean val) setPaintLabels (boolean val); Events: * when slider moves, the value of slider moves between min and max * when value changes, a ChangeEvent happens * listeners must implement the ChangeListener interface * this interface contains one method: void stateChanged(ChangeEvent e) * slider method int getValue() provides slider value

Borders Place a border around a panel to group its contents visually EtchedBorder : theree-dimensional etched effect Can add a border to any component, but most commonly to panels: TitledBorder : a border with a title Jpanel panel = new JPanel (); panel.setBorder(new EtchedBorder ()); panel.setBorder(new TitledBorder(new EtchedBorder(), “Size”));

Advanced Topic: Layout Management Step 1: Make a sketch of your desired component layout

Advanced Topic: Layout Management Step 2: Find groupings of adjacent components with the same layout

Advanced Topic: Layout Management Step 3: Identify layouts for each group Step 4: Group the groups together Step 5: Write the code to generate the layout

Menus Pull-Down Menus

Swing provides pull-down menus To build a menu: Create a menu bar JMenuBar object Add the menu bar to a frame use JFrame method setJMenuBar Create each menu and add it to menubar JMenu object represents menu use JMenuBar method add Add menu items to the menu JMenuItem object represents menu item use JMenu method add Install Action Listeners to JMenuItem objects useJMenuItem addActionListener methods Add action listeners only to menu items, not to menus or the menu bar

EXAMPLE (runnable code in MenuColor.java) JMenuBar mbar = new JMenuBar(); //create menu bar fr. setJMenuBar(mbar); //add to frame JMenu optMenu = new JMenu("Options"); //new menu mbar.add(optMenu); // add to menu bar //create and set up 2 items JMenuItem cpan = new JMenuItem("Color panel"); CPListen cpl = new CPListen(); //CPListen is ActionListener class cpan.addActionListener(cpl); optMenu.add(cpan); JMenuItem calpan = new JMenuItem("Calorie burn"); CalPListen calpl = new CalPListen(); //CalPListen is ActionListener class calpan.addActionListener(calpl); optMenu.add(calpan);