GUI Programming Two forms of graphics in Java – Graphics object to draw on – GUI components to interact with we visit GUI in chapter 12 and Graphics in.

Slides:



Advertisements
Similar presentations
Graphical User Interfaces
Advertisements

Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
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.
Graphical User Interfaces CS 2110 Spring Ivan Sutherland: “Sketchpad”,
Corresponds with Chapter 12
GUI programming AWT(Abstract Windows Toolkit)-GUI components library when Java was introduced AWT was replaced by Swing components import javax.swing.*;
Swinging Into Swing Leo S. Primero III. Understanding what Swing Is Swing is a package that lets you create applications that use a flashy Graphical User.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 GUI Basics.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Java Programming Chapter 10 Graphical User Interfaces.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Standard Graphics in Java.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Creating GUIs in Java Using.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
GUI Basics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 12 GUI Basics.
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
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.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
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.
MIT-AITI 2004 – Lecture 16 Introduction to Swing.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Csc Basic Graphical User Interface (GUI) Components.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Basics of GUI Programming Chapter 11 and Chapter 22.
J McQuillanSE204:2004/2005: Lecture 3Slide 1 Specialised Components Can create specialised components. Do this by subclassing the component that you are.
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.
Programming 2 LAB TA: Nouf Al-Harbi NoufNaief.net :::
Sadegh Aliakbary Sharif University of Technology Fall 2011.
CSI 3125, Preliminaries, page 1 Layout Managers. CSI 3125, Preliminaries, page 2 Layout Managers The LayoutManagers are used to arrange components in.
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
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.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
Chapter 7 A First Look at GUI Applications Layout Managers.
Modern Programming Language Java
Java Swing.
Chapter 13: Advanced GUIs and Graphics
Advanced Programming in Java
Chapter 12 GUI Basics.
Advanced GUIs and Graphics
Graphical User Interface
TA: Nouf Al-Harbi NoufNaief.net :::
Presentation transcript:

GUI Programming Two forms of graphics in Java – Graphics object to draw on – GUI components to interact with we visit GUI in chapter 12 and Graphics in chapter 13 in order to use either, you have to insert your GUI components or draw upon a suitable surface – a GUI container You can only place GUI components (JComponents) onto JFrames, JPanels and Japplets You can only draw using the Graphics object which is only available in panels and applets Dimension, Graphics, Color, Font and FontMetrics are known as helper classes and are not used in isolation

Swing vs AWT In early versions of Java, all of the GUI + Graphics classes were defined in the java.awt library – awt = abstract windows toolkit Later versions defined new and better classes in swing – To differentiate between them, the newer classes start with the letter J (JFrame, JPanel, JButton, etc) – You will need to use both because some classes are currently only defined in AWT (Color, Font, Graphics) – The swing classes are better: they are more robust, flexible, versatile and the awt classes will eventually be deprecated NOTE: the most recent version of Java contains even newer components than the swing classes so even the swing classes may eventually be deprecated

Swing GUI Components

Creating a GUI/Graphics In order to place GUI components or a Graphics object, you must place this into a container – JFrame, JPanel, JApplet – JPanels cannot be directly made visible so you must insert a JPanel onto a JFrame or JApplet So, start with a JFrame – Add to the JFrame a subclass of type JPanel – Define the subclass (either separately or as a nested inner class to the code where you create your JFrame) – Add JComponents to your JPanel (including other JPanels or a Graphics object) the amount of code you need to define, organize and place the components is going to be large but necessary – the good news is that it is easy, just a lot of code

Example import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); MyPanelClass panel = new MyPanelClass( ); frame.add(panel); frame.setVisible(true); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); } private static class MyPanelClass extends Jpanel { // constructor and needed methods here } String for title bar Size in pixels Makes JFrame appear Allows program to exit upon closing JFrame NOTE: if size (in setSize) is too small, the JVM will do the best it can to place items into the frame and/or panel

JFrame Methods We already saw most of the methods (listed below) in use in the previous example – setLocationRelativeTo and setLocation allow you to position the JFrame once it appears on your desktop otherwise the JFrame appears in the upper left hand corner of your desktop setLocationRelativeTo centers the JFrame in the middle of the desktop setLocation lets you specify the pixel location in x, y coordinates if you use setLocationRelativeTo(null), place setSize before it

Adding Components to your JFrame Once you have created a GUI Component (e.g., a JButton), you add it to your JFrame using the add method – frame.add(item); You can control how items appear within the JFrame using a LayoutManager (we’ll cover that shortly) – managing items on a JFrame can be a challenge when you have a lot of items that you want to form into some kind of pattern (such as a set number of rows and columns) Instead, use JPanels as intermediate containers – create a JPanel – add components to the JPanel – add the JPanel to the JFrame – we can also place JPanels into other JPanels NOTE: a GUI component can only be placed onto one container, it cannot be shared among multiple containers

Example import javax.swing.*; public class JFrameExample1 { public static void main(String[] args) { JFrame frame=new JFrame("example 1"); JPanel panel1=new JPanel(); JButton button1=new JButton("button 1"); JButton button2=new JButton("button 2"); JButton button3=new JButton("button 3"); panel1.add(button1); panel1.add(button2); panel1.add(button3); frame.add(panel1); frame.setSize(300,100); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

Layout Managers The LayoutManager is a helper class from java.awt There are 3 types of LayoutManagers (subclasses) – FlowLayout – the default form, elements added to the same row until the row is full and then starts the next row – GridLayout – specify the number of rows, r, and columns, c fill row by row (c items per row), r or c can be 0 but not both if one is 0 then the other is a “fixed” dimension and the 0 becomes “as needed”, if r and c are not zero, then r is “as needed” while c is fixed – BorderLayout – uses 5 sections, NORTH, CENTER, SOUTH, EAST and WEST to position components with BorderLayout, the add instruction requires the location as in add(item1,BorderLayout.NORTH); or add(item5,BorderLayout.EAST); To set the layout, you can do this when you construct the JPanel or later –JPanel p1=new JPanel(new GridLayout(3,2)); –p1.setLayout(new BorderLayout( ));

More on Layout Each of the LayoutManager constructors also permit two integer values: hgap and vgap – How much vertical and horizontal space to place between items these ints are the number of pixels inserted between items – All of the LayoutManager classes have methods to setHgap, setVgap GridLayout also has methods of setRows, SetColumns – FlowLayout also permits an alignment align all items inserted to left, center or right this is specified as FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT in the FlowLayout constructor you can only specify hgap & vgap in the FlowLayout constructor if you also use alignment, otherwise you must use setHgap and setVgap there is also a setAlignment method for FlowLayout if you choose to not set the alignment in the constructor – When adding an item to a container using BorderLayout, if you omit the location, it defaults to BorderLayout.CENTER

Extending JFrame Although our previous example was sufficient to create a JFrame and add components onto it, the author recommends the following approach – Create a class which extends JFrame – In the constructor, add your GUI components – Create a main method which creates an instance of your JFrame subclass, set its title, size, location, close and visible The reasons for this approach are – By creating a subclass, we can further extend that subclass if needed – The subclass can be reused This GUI is created by the example code on the next slide

import javax.swing.*; import java.awt.*; public class JFrameExample1 { public static void main(String[] args) { MyFrame frame=new MyFrame(); frame.setTitle("My JFrane"); frame.setSize(300,120); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static class MyFrame extends JFrame { public MyFrame() { // super( ); setLayout(new FlowLayout (FlowLayout.RIGHT,10,5)); add(new JButton("Button 1")); add(new JLabel("This is a JLabel")); add(new JButton("Button 2")); add(new JLabel("another JLabel")); }

The Need for JPanels import java.awt.*; import javax.swing.*; public class TestPanels extends JFrame { public TestPanel1() { Jpanel p1=new JPanel(new FlowLayout()); for (int i = 1; i <= 9; i++) { p1.add(new JButton("" + i)); } p1.add(new JButton("" + 0)); p1.add(new JButton("Start")); p1.add(new JButton("Stop")); p1.add(new JTextField("Time to be displayed here")); p1.add(new JButton("Food to be placed here")); } /** Main method */ public static void main(String[] args) { TestPanels frame = new TestPanels(); // details omitted } The book presents a microwave oven GUI If we try to place all of the components into one panel, it looks awful (see below) The author’s code, using 2 JPanels with 2 layout managers looks much better (see pages )

Another Approach Instead of creating a class which extends JFrame, we can also or instead create a class which extends JPanel, we insert components in our JPanel constructor – main creates a JFrame and adds an instance of our JPanel – This allows us to actually define multiple JPanel subclasses and insert them all into a single JFrame import java.awt.*; import javax.swing.*; public class GUIExample { public static void main(String[] args) { JFrame frame=new JFrame(“title here"); frame.setSize(300,150); MyPanel1 p1=new MyPanel1( ); MyPanel2 p2=new MyPanel2( ); frame.add(p1); frame.add(p2); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static class MyPanel1 extends JPanel {…} public static class MyPanel2 extends JPanel {…} }

GUI Components JLabel – Used to display text or icons (images) – Item can be changed using setText or setIcon JTextField – Used to provide a box for either input or output – Messages getText to return the input or setText to change the text in the box – Constructor allows you to specify a width otherwise the size of the field is set to the initial string you can specify a string and the column width if you want a larger box – Input will be treated as a String (you have to parse numbers into a proper form such as doing Integer.parseInt(jtf.getText( )); –jtf.setEditable(true/false); allows you to control whether the user can enter something into the textfield or not JButtons – Can display text or icons (or both) and align them horizontally and/or vertically – Can alter the images when mouse is rolling over or pressing the JButton

public static class GuiPanel extends JPanel { private JButton activate, clear, quit; private JTextField jtf; private JLabel lab; public GuiPanel() { activate=new JButton("Activate"); clear=new JButton("Clear"); quit=new JButton("Quit"); jtf=new JTextField("",15); lab=new JLabel(" "); JPanel buttons=new JPanel(new GridLayout(3,1)); buttons.add(activate); buttons.add(clear); buttons.add(quit); JPanel fields=new JPanel(new GridLayout(2,1)); fields.add(jtf); fields.add(lab); JPanel whole=new JPanel(new BorderLayout()); whole.add(buttons,BorderLayout.EAST); whole.add(fields,BorderLayout.CENTER); add(whole); }

More GUI Components JCheckBox & JRadioButton – Both of these are types of toggle buttons – each button is in one of two states – selected or not – For the JRadioButtons, you put them into a group so that only one JRadioButton in the group can be selected at a time Like JButtons, these can have text and/or icons – You can default each JCheckBox to being selected or not selected – You can default a single JRadioButton in a group to being selected or have all in the group be unselected initially LineBorders – You can place a line border around a component or JPanel – You specify the border’s color and width You can also change the mouse cursor’s appearance when you move it over a component – component.setCursor(new Cursor(…)); – In the constructor, you can specify Cursor.HAND_CURSOR Cursor.CROSSHAIR_CURSOR,, Cursor.TEXT_CURSOR and Cursor.MOVE_CURSOR

public static class GuiPanel extends JPanel { JCheckBox b1, b2, b3, b4; JRadioButton b5, b6, b7; public GuiPanel() { b1=new JCheckBox("Option 1");... b5=new JRadioButton("Selection a");... ButtonGroup rads=new ButtonGroup(); rads.add(b5);... JPanel p1=new JPanel(new GridLayout(4,1)); p1.add(b1);... JPanel p2=new JPanel(new GridLayout(3,1)); p2.add(b5);... JPanel whole=new JPanel(); whole.add(p1); whole.add(p2); add(whole); }

Helper Classes Like the border and cursor, other helper classes are not used directly in a container but can be applied to components – Color – define the color of a component in red, green, blue (3 int values between 0 and 255 where 0 is “full” and 255 is “none”) as in new Color(0,255,128); – You can establish the foreground and background color of components using component.setForeground(new Color(…)); and component.setBackground(new Color(…)); – Font – specify a font type, style and size for text as in new Font(SansSerif, Font.BOLD, 24); bold and italics both require using Font.BOLD + Font.ITALIC – ImageIcon – to use an image, you generate an icon using new ImageIcon(filename) – in Java, the only allowable file types are gif, jpg, png (as we saw, images can be inserted into JLabels and the various types of buttons)

Common Attributes of JComponents Study the UML notation on page 462 – you will find all Components have getWidth, getHeight, getX and getY methods – along with get and set methods for instance data font, background, foreground, preferredSize, visible and cursor (mouse cursor style) Containers are subclasses – these all have methods to add a component, add a component at a specific index, remove a component, get a layout (getLayout) and set the layout (setLayout) JComponents are subclasses of Container – these have methods of getToolTipText, setToolTipText, getBorder and setBorder See figure on page 463 and the corresponding code in listing 12.7 (pages )