Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.

Slides:



Advertisements
Similar presentations
Drawing in a frame – Java GUI
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
© L.Lúcio, An example GUI in Java n Two graphic libraries in Java u AWT u Swing n Swing is more recent than AWT: u Built on top of AWT classes;
Gui Interfaces a la Swing Up to speed with Swing by Steven Gutz is a good source It don’t mean a thing if it ain’t got that swing Duke Ellington.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Contructing GUI’s in Java Implemented in the Swing API Imported into your programs by: import javax.swing.*; Most Swing programs also need the AWT packages.
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.
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.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Lesson 27: Introduction to the Java GUI. // helloworldbutton.java import java.awt.*; import javax.swing.*; class HelloButton{ public static void main.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Interfaces & Polymorphism part 2:
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.
Lesson 36: The calculator – Java Applets. 1. Creating Your First Applet HelloWorldApp is an example of a Java application, a standalone program. Now you.
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.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
GUI programming Graphical user interface-based programming.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
CS Lecture 01 Frames and Components and events Lynda Thomas
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
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.
The Drawing program – Java Applets
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.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
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.
Lesson 39: More wrapup on GUIs. 1.This presentation will focus on the decisions around software architecture and the decisions that will drive the code.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
For (int i = 1; i
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.
CompSci Event Handling. CompSci Event Handling The Plan  Sequential (Single Thread) Model  Event Model  Making the GUI interactive  Examples.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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)
Lesson 33: Layout management and drawing – Java GUI.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Design Applet based java program to find the area and perimeter of a rectangle given its length and width. Java GUI.
Multiple buttons and action calls
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Graphical User Interfaces
Java Applet What is a Java Applet? How is applet compiled?
Web Design & Development Lecture 11
Graphical User Interface (pronounced "gooey")
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Event-driven programming for GUI
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Graphical user interface-based programming
Steps to Creating a GUI Interface
The calculator – Java GUI
A Quick Java Swing Tutorial
CiS 260: App Dev I Chapter 6: GUI and OOD.
Graphical User Interface
Presentation transcript:

Lesson 35: Review of the Java GUI

The JFrame, Container and JButton

// helloworldbutton.java import java.awt.*; import javax.swing.*; class HelloButton{ public static void main (String[] args){ JFrame frame = new JFrame("HelloButton"); Container pane = frame.getContentPane(); JButton hello = new JButton("HelloWorld"); pane.add(hello); frame.pack(); frame.show(); } The Java Button frame.setSize(300,200);

The Swing library Any program that uses Swing to create a window enters a separate thread of execution that enters an infinite loop, looking for events such as mouse movements, button clicks or key presses. This is like having to workers executing the program: –One for the main() –One for watching for events This results in an event driven program When main() is finished, the program still is executing the “listening” part of the library object.

The Swing library All Swing components are event sources that can be observed or listened to. To use the event, we need to tell the source which object to notify when an event occurs. By default the JButton reacts to a mouse click by changing its appearance. JButtons are also the source of java.awt.event.ActionEvent objects. An ActionEvent is generated by a button when you click the button with a mouse. Objects that can receive events are called listeners. Different type of events have different listeners.

// HelloGoodBye.java import java.awt.*; import javax.swing.*; class HelloGoodBye{ public static void main (String[] args){ JFrame frame = new JFrame("HelloGoodBye"); Container pane = frame.getContentPane(); JButton hello = new JButton("Hello world!!"); GoodBye listener = new GoodBye(); hello.addActionListener(listener); pane.add(hello); frame.setSize(200,75); frame.show(); } Now we have a button, but no action for the object named listener from the GoodBye class

// GoodBye.java import java.awt.event.*; class GoodBye implements ActionListener{ public void actionPerformed(ActionEvent e) { System.out.println(“Goodbye !”); System.exit(0); }

The Result

The steps Create a button with new Jbutton (“some label”) Get the Container for the Jframe using getContentPane() Add the button to the content pane of the Jframe with add() Create an ActionEventListener class by –Adding implements ActionEventListener to the lcass declaration and –Defining an actionPerformed method Add the listener object to the list of listeners for the button by calling button.addActionListener(listener), where the button is the name we gave our button, and listener is an instance of the class we created to be executed when the button was clicked (the GoodBye class).

Many Buttons // ManyButtons.java import java.awt.*; import javax.swing.*; class ManyButtons{ public static void main (String[] args){ JFrame frame = new JFrame("myCalculator"); Container pane = frame.getContentPane(); JButton exit = new JButton("Exit"); GoodBye listener = new GoodBye(); exit.addActionListener(listener); JButton myAddition = new JButton("2+2"); Addition listener1 = new Addition(); myAddition.addActionListener(listener1); JButton mySubtraction = new JButton("123-12"); Subtraction listener2 = new Subtraction(); mySubtraction.addActionListener(listener2); pane.add(exit); pane.add(myAddition); pane.add(mySubtraction); frame.pack(); frame.show(); } How not to engineer the application

// Addition.java import java.awt.event.*; class Addition implements ActionListener{ public void actionPerformed(ActionEvent e) { System.out.println("The answer is 4"); System.exit(0); } // Subtraction.java import java.awt.event.*; class Subtraction implements ActionListener{ public void actionPerformed(ActionEvent e) { System.out.println("The answer is 111"); System.exit(0); } // GoodBye.java import java.awt.event.*; class GoodBye implements ActionListener{ public void actionPerformed(ActionEvent e) { System.out.println("Goodbye!"); System.exit(0); } How not to engineer the application

The JTextField, JLabel and gridLayout

// MiniCalc.java - demo gridlayout import java.awt.*; import javax.swing.*; class MiniCalc{ public static void main (String[] args){ JFrame frame = new JFrame("MiniCalc"); Container pane = frame.getContentPane(); //Creating the major components JTextField firstNumber= new JTextField(20); JTextField secondNumber= new JTextField(20); JTextField result= new JTextField(20); JButton addButton = new JButton("Add"); JButton subButton = new JButton("Subtract"); pane.setLayout(new GridLayout(4,2)); pane.add(new JLabel("Enter a number")); pane.add(firstNumber); pane.add(new JLabel("Enter a number")); pane.add(secondNumber); pane.add(new JLabel("Result")); pane.add(result); pane.add(addButton); pane.add(subButton); DoMath listener = new DoMath(firstNumber, secondNumber, result); subButton.addActionListener(listener); addButton.addActionListener(listener); frame.pack(); frame.show(); } Dividing the Container in a grid with 4 rows and 2 columns

// DoMath.java import javax.swing.*; import java.awt.event.*; class DoMath implements ActionListener{ DoMath(JTextField first, JTextField second, JTextField result){ inputOne = first; inputTwo = second; output = result; } public void actionPerformed(ActionEvent e){ double first, second; first = Double.parseDouble(inputOne.getText().trim()); second = Double.parseDouble(inputTwo.getText().trim()); if (e.getActionCommand().equals("Add")) output.setText(String.valueOf(first+second)); else output.setText(String.valueOf(first-second)); } private JTextField inputOne, inputTwo, output; } Simple if…else statement

Running the application

The layout manipulations

The LEFT layout // FlowLayoutTest.java - demo flowlayout import java.awt.*; import javax.swing.*; class FlowLayoutTest{ public static void main (String[] args){ JFrame frame = new JFrame("FlowLayoutTest.LEFT"); Container pane = frame.getContentPane(); pane.setLayout(new FlowLayout(FlowLayout.LEFT)); pane.add(new JButton("Button 1")); pane.add(new JLabel("Label 2")); pane.add(new JButton("Button 3")); pane.add(new JLabel("Label 4")); pane.add(new JButton("Button 5")); frame.pack(); frame.show(); } CENTER LEFT

Adding buttons to actions and frames -Another example

Adding a button to StartTest // StarTestQuit.java - add a quit button to StartTest import java.awt.*; import javax.swing.*; class StarTestQuit{ public static void main (String[] args){ JFrame frame = new JFrame("StartTest"); Container pane = frame.getContentPane(); Star star = new Star(); JButton Quit = new JButton("Quit"); pane.setLayout(new FlowLayout()); Quit.addActionListener(new GoodBye()); pane.add(Quit); pane.add(star); frame.pack(); frame.show(); } Adding an actionlistener to the button based on the GoodBye class (from earlier class example) Adding the button and the star to the container Showing the frame Packing the frame to smallest size

ProgramCompile Run Exit

A simple Drawing program

Drawing in a frame // StarTest.java - display a starburst import java.awt.*; import javax.swing.*; class StarTest{ public static void main (String[] args){ JFrame frame = new JFrame("StartTest"); Container pane = frame.getContentPane(); Star star = new Star(); pane.add(star); frame.pack(); frame.show(); }

The Star Class // Star.java - draws a star import javax.swing.*; import java.awt.*; class Star extends JComponent{ public void paint (Graphics g){ double x1, x2, y1, y2; for (double angle=0; angle<Math.PI; angle = angle + Math.PI / 16) { x1=Math.cos(angle) * RADIUS + RADIUS; y1=Math.sin(angle) * RADIUS + RADIUS; x2=Math.cos(angle + Math.PI) * RADIUS + RADIUS; y2=Math.sin(angle + Math.PI) * RADIUS + RADIUS; g.drawLine((int)x1, (int)y1,(int)x2, (int)y2); } public Dimension getMinimumSize(){ return new Dimension(2 * RADIUS, 2 * RADIUS); } public Dimension getPreferredSize(){ return new Dimension(2 * RADIUS, 2 * RADIUS); } private static final int RADIUS = 100; }

An interactive Drawing program

// SimplePaint.java - drawing with a mouse import java.awt.*; import javax.swing.*; class SimplePaint{ public static void main (String[] args){ JFrame frame = new JFrame("SimplePaint"); Container pane = frame.getContentPane(); DrawingCanvas canvas = new DrawingCanvas(); PaintListener listener=new PaintListener(); canvas.addMouseMotionListener(listener); pane.add(canvas); frame.pack(); frame.show(); }

// DrawingCanvas.java - a blank canvas import javax.swing.*; import java.awt.*; class DrawingCanvas extends JComponent{ public Dimension getMinimumSize(){ return new Dimension(SIZE, SIZE); } public Dimension getPreferredSize(){ return new Dimension(SIZE, SIZE); } private static final int SIZE=500; }

// PaintListener.java import java.awt.*; import java.awt.event.*; class PaintListener implements MouseMotionListener{ public void mouseDragged(MouseEvent e) { DrawingCanvas canvas = (DrawingCanvas)e.getSource(); Graphics g = canvas.getGraphics(); g.fillOval(e.getX()-radius, e.getY() - radius, diameter, diameter); } public void mouseMoved(MouseEvent e){} private int radius =3; private int diameter = radius*2; } This class implements the interface MouseMotionListener The interface MouseMotionListener requires that two methods are implemented: 1)mouseDragged (button clicked and held down) 2)mouseMoved (no button clicked and held down)

The outcome

Some problems with our simple drawing program…

Everytime a window is placed over the drawing, the text that was overlapped is removed when the window becomes active again

// PaintListener2.java - paints on a DrwaingCanvas2 // and it is associated with an offscreenImage. import java.awt.*; import java.awt.event.*; class PaintListener2 implements MouseMotionListener{ public void mouseDragged(MouseEvent e) { DrawingCanvas2 canvas = (DrawingCanvas2)e.getSource(); Graphics g = canvas.getGraphics(); g.fillOval(e.getX()-radius, e.getY() - radius, diameter, diameter); // duplicating the drawing on the offscreenImage Image image= canvas.getOffscreenImage(); g = image.getGraphics(); g.fillOval(e.getX()-radius, e.getY() - radius, diameter, diameter); } public void mouseMoved(MouseEvent e){} protected int radius =3; protected int diameter = radius*2; }

// SimplePaint2.java - drawing with a mouse import java.awt.*; import javax.swing.*; class SimplePaint2{ public static void main (String[] args){ JFrame frame = new JFrame("SimplePaint"); Container pane = frame.getContentPane(); DrawingCanvas2 canvas = new DrawingCanvas2(); PaintListener2 listener=new PaintListener2(); canvas.addMouseMotionListener(listener); pane.add(canvas); frame.pack(); frame.show(); }

// DrawingCanvas2.java - a blank canvas that remembers // drawing operations using an offscreen image import javax.swing.*; import java.awt.*; class DrawingCanvas2 extends JComponent{ public void paint(Graphics g){ if (offscreenImage!=null) g.drawImage(offscreenImage,0,0,SIZE,SIZE,null); } public Image getOffscreenImage(){ if (offscreenImage==null) offscreenImage=createImage(SIZE,SIZE); return offscreenImage; } public Dimension getMinimumSize(){ return new Dimension(SIZE, SIZE); } public Dimension getPreferredSize(){ return new Dimension(SIZE, SIZE); } private static final int SIZE=500; private Image offscreenImage; }

Everytime a window is placed over the drawing, the offscreenimage is called when the window becomes active again

Next the Java Applet