GUI Tutorial 2. What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Event Handling Events and Listeners Timers and Animation.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
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.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
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.
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
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.
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,
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.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
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.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
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)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
1 Lecture 25 Listening to buttons and mice Quotes by Tony Hoare There are two ways of constructing a software design: (1) make it so simple that there.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Review_6 AWT, Swing, ActionListener, and Graphics.
Computer Science 209 GUIs Model/View/Controller Layouts.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
GUI Tutorial 1. A Bit of Philosophy on what to Teach  There are numerous libraries, frameworks, options  Modern GUIs are often developed using XML (e.g.,
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
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.
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
GUI Programming in Java Hao Jiang Boston College April, 2009.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
A First Look at GUI Applications
Advanced User Interfaces
Chapter 13: Advanced GUIs and Graphics
Components.
Advanced Programming in Java
Advanced GUIs and Graphics
Presentation transcript:

GUI Tutorial 2

What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming  action listener for buttons  Simple pop-up dialogs (JOptionPane)  Layout managers  BorderLayout, FlowLayout, GridLayout  JPanel  JTextField, JLabel, Jbutton, JCheckBox, JComboBox, JRadioButton, JRadioGroup  Borders and Fonts

What will we do this time?  Add actions to other controls  JMenu/JMenuItem  JTextArea  Panel Communication  Simple Drawing

Add a menu  Menus are added to the JFrame – not a JPanel  Menus are added via setJMenuBar – not add  The menu system consists of one JMenuBar and one or more objects of type JMenu containing JMenuItem  In the JFrame constructor: JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(createFileMenu());

The menu private JMenu createFileMenu() { JMenu menu = new JMenu("File"); menu.add(createFileExitItem()); return menu; } private JMenuItem createFileExitItem() { JMenuItem item = new JMenuItem("Exit"); class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } item.addActionListener(new MenuItemListener()); return item; }

Coordination between Objects (JPanel) Main panel Control Panel

Objects coordinate via function calls (“messages”)  Remember that communication between objects can be thought of as message passing. For our program, we’ll create a DisplayPanel to display a summary of the choices. This panel should be updated every time a change is made to one of the panels. DisplayPanel ToFromPanel Update the status PreferencePanel WillDrivePanel

Panel Communication - UML

First create a DisplayPanel public class DisplayPanel extends JPanel { // Variables for message private String name, fromCity,toCity, willDrive, music; // display – multiple lines allowed in JTextArea private JTextArea display; public DisplayPanel() { // set some default values name = "Someone"; fromCity = "Somewhere"; toCity = "Somewhere"; willDrive = "needs a ride"; music = "no music"; display = new JTextArea(2, 20); display.setLineWrap(true); // uses multiple lines display.setWrapStyleWord(true); // breaks on word boundaries updateDisplay(); add(display ); }

Update method private void updateDisplay() { display.setText(name + " " + willDrive + " from " + fromCity + " to " + toCity + " and prefers " + music); } } // end class

Let’s display  Update the constructor of the JFrame (CarpoolGUI) // Create DisplayPanel first DisplayPanel dp = new DisplayPanel(); add(dp, BorderLayout.SOUTH); // The rest has not changed… yet! PreferencePanel pPanel = new PreferencePanel(); add(pPanel, BorderLayout.EAST); ToFromPanel tfPanel = new ToFromPanel(); add(tfPanel, BorderLayout.CENTER); WillDrivePanel wdPanel = new WillDrivePanel(); add(wdPanel, BorderLayout.NORTH);

All panels now display Now we need to add some action

Panel communication  Other panels will need to be able to send values to set the variables for this message. Use Eclipse to create setters for DisplayPanel.

How can other panels update the display?  Other panels will need to have access to the DisplayPanel. How to do this? Send a reference into the constructor.  In the PreferencePanel: private DisplayPanel dp; public PreferencePanel(DisplayPanel dp) { this.dp = dp;...  Update all the panels. notice use of this keyword

How to access the DisplayPanel  Update the constructor of the JFrame (CarpoolGUI) // Create DisplayPanel first DisplayPanel dp = new DisplayPanel(); add(dp, BorderLayout.SOUTH); // Send it into other 3 panels PreferencePanel pPanel = new PreferencePanel(dp); add(pPanel, BorderLayout.EAST); ToFromPanel tfPanel = new ToFromPanel(dp); add(tfPanel, BorderLayout.CENTER); WillDrivePanel wdPanel = new WillDrivePanel(dp); add(wdPanel, BorderLayout.NORTH);

Add action – radio button  Need a radio listener private class RadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (musicButton.isSelected()) dp.setMusic("music"); else dp.setMusic("no music"); } Need to add listener to each button RadioListener listener = new RadioListener(); musicButton.addActionListener(listener); noMusicButton.addActionListener(listener);

Need to call updateDisplay  In DisplayPanel, the setters need to cause the display to update, for example: public void setMusic(String music) { this.music = music; updateDisplay(); }

Add action - CheckBox private class CheckboxListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (willDriveCB.isSelected()) dp.setWillDrive("will drive"); else dp.setWillDrive("needs a ride"); }  Add the action listener to our check box: willDriveCB.addActionListener(new CheckboxListener());

Add action – Focus Listener  The Java interpreter knows which component has the “focus” – e.g., if the mouse is in the name field, it has focus. If you click on some other field, the name field “loses” focus.  FocusListener is an interface that can be used to respond to focus events.  Two methods must be defined: focusGained and focusLost. You must write both of these methods, even if you’re only interested in one type of event. The other method may have an empty body.  Be sure to include java.awt.event.*; (or specific classes)

Our focus listener private class NameListener implements FocusListener { // We don’t care when we get focus public void focusGained(FocusEvent e) {} // When we lose focus, need to update the display public void focusLost(FocusEvent e) { dp.setName(name.getText()); }  Add the focus listener to the name field. Since only one component uses this listener, we don’t bother creating a local variable. name.addFocusListener(new NameListener());

Add action - ComboBox  Fires both action events and item events. Item events respond to any change of state, whether caused by the program or the user. Action events are called when the user interacts with the component.  For user actions, both events will be generated. You should only listen for one type of event. Typically you’re interested in the user’s actions, so use an action listener.

Add action - ComboBox  We’ll use the same listener for both boxes. We’ll use the ActionEvent getSource method to determine which one changed. private class ComboListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == toCity) dp.setToCity(toCity.getSelectedItem().toString()); else dp.setFromCity(fromCity.getSelectedItem().toString()); }  Add the listener to both combo boses. ComboListener listener = new ComboListener(); fromCity.addActionListener(listener); toCity.addActionListener(listener);

That’s all, folks!

Eclipse Hint:  Edit > Select All (Ctrl-A)  Source > Correct Indentation (Ctrl-I)  All programs that are turned in for grading should be neatly formatted!

Drawing

The Graphics class –Get the concept! From the Sun documentation: The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto off-screen images. A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties:  The Component object on which to draw.  A translation origin for rendering and clipping coordinates.  The current clip.  The current color.  The current font.  The current logical pixel operation function (XOR or Paint).  The current XOR alternation color (see setXORMode(java.awt.Color)).setXORMode(java.awt.Color)

Graphics class continued  Sample methods:  drawImage  drawLine/fillLine  drawOval/fillOval  drawRect/fillRect  drawString  setColor  setFont x: 0.. y0..y0.. Example line from ~10 10 to ~20 20

Graphics class – VERY IMPORTANT  Graphics is abstract, can’t call constructor directly  Can be obtained by calling getGraphics on a component  Automatically created for the paintComponent method of any class that extends JComponent (either directly or indirectly)  paintComponent is called automatically when the component needs to be redrawn  initial load  when repaint() method called  when screen is resized etc.  BEST STRATEGY: write the paintComponent method, call repaint() when you need to update the drawing usually don’t need to!

Drawing – Basic Strategy 1. As always, create a JFrame 2. Create a class that extends JComponent or JPanel to contain your drawing 3. Add that JPanel to your JFrame (often to the CENTER) 4. In that class, override paintComponent(Graphics g) method. 5. Inside the method, use draw commands as needed to create your image (e.g., g.drawLine(…)) 6. paintComponent will be called automatically when the screen needs to be redrawn (e.g., when first displayed, if minimized then maximized, etc). 7. Inside paintComponent, call super.paintComponent for required housekeeping – IMPORTANT! 8. If you need to update the drawing, do not call paintComponent directly. Instead, call repaint(). Example: change player’s position in Clue, call repaint() on your board (either board.repaint(); or repaint(); depending on what method is updating the player’s location).

Create a JPanel import javax.swing.*; import java.awt.*; public class DrawPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.drawRect(10, 15, 20, 20); } Remember this for housekeeping (e.g., background)

Create a frame, add the component public class DrawFrame extends JFrame { private DrawPanel drawPanel; public DrawFrame() { drawPanel = new DrawPanel(); // paintComponent will automatically be // called 1 time add(drawPanel, BorderLayout.CENTER); setSize(300, 300); } public static void main(String[] args) { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

Let’s make some changes public class DrawPanel extends JPanel { private int x, y; public DrawPanel() { x = 10; y = 15; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.drawRect(x, y, 20, 20); } public void translate(int dx, int dy) { x += dx; y += dy; // Must include this to see changes repaint(); }

And call it from main… public void updateDrawing(int dx, int dy) { drawPanel.translate(dx, dy); } public static void main(String[] args) { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // This will cause rectangle to display in new location frame.updateDrawing(100, 100); }

Let’s put in a delay public void updateDrawing(int dx, int dy) { this.dx = dx; // need to add instance variables this.dy = dy; // 1000 millisecond delay Timer t = new Timer(1000, new TimerListener()); t.start(); } private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { drawPanel.translate(dx, dy); } Be sure to get javax.swing.Timer

Complete Program public class DrawFrame extends JFrame { private DrawPanel drawPanel; private int dx, dy; public DrawFrame() { drawPanel = new DrawPanel(10, 15); add(drawPanel, BorderLayout.CENTER); setSize(300, 300); } public void updateDrawing(int dx, int dy) { this.dx = dx; this.dy = dy; Timer t = new Timer(1000, new TimerListener()); t.start(); } private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { drawPanel.translate(dx, dy); } } public static void main(String[] args) { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.updateDrawing(5, 10); } public class DrawPanel extends JPanel { private int x, y; public DrawPanel(int x, int y) { this.x = x; this.y = y; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.drawRect(x, y, 20, 20); System.out.println("Called paint component"); } public void translate(int dx, int dy) { x += dx; y += dy; // Must include this to see changes repaint(); }