Advanced Java Unit 6: Review of Graphics and Events
|
|
- Shona Melissa McKinney
- 6 years ago
- Views:
Transcription
1 Advanced Java Unit 6: Review of Graphics and Events This is a review of the basics of writing a java program that has a graphical interface. To keep things simple, all of the graphics programs will follow a similar pattern: Our main class will extend JFrame. We will add one JPanel object to the JFrame and use the null layout to simplify placement of buttons, text fields, etc. When/if we need somewhere to draw then we will write a class that extends JPanel, create one object of that class and add it to the JPanel that is in the JFrame. Example 1. Copy DemoProgram and Convert classes and then execute the main method. Here is the code from the DemoProgram along with explanations for some of the code. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Demo_Frame extends JFrame { private JTextField txtmph, txtfps; // instance variables so the inner class can use them public static void main(string[] args) { // main method here to be more concise Demo_Frame f = new Demo_Frame(); f.display(); public Demo_Frame(){ setdefaultcloseoperation(exit_on_close); // quits when X is clicked settitle( "Convert" ); JPanel jp = new JPanel(); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 225, 165 ) ); // sets panel s width, height jp.setlayout( null ); // see page 3 txtmph = new JTextField(); txtmph.setbounds( 25, 25, 100, 25 ); JLabel lblmph = new JLabel("MPH"); lblmph.setbounds( 150, 25, 40, 25 ); // sets x, y, width, and height JButton button = new JButton( "Convert MPH to FPS" ); button.setbounds( 25, 65, 150, 35 ); button.addactionlistener( new ButtonListener() ); The argument to addactionlistener must be an object that implements the ActionListener interface. The ButtonListener class is defined below. 1
2 txtfps = new JTextField(); txtfps.setbounds( 25, 115, 100, 25 ); txtfps.seteditable( false ); JLabel lblfps = new JLabel("FPS"); lblfps.setbounds( 150, 115, 40, 25 ); jp.add( txtmph ); jp.add( lblmph ); jp.add( button ); jp.add( txtfps ); jp.add( lblfps ); // adds each component to the panel getcontentpane().add( jp ); // adds the panel to the frame pack(); // causes the frame to wrap and resize around the panel public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); When using Swing classes, all code that modifies the user interface must/should run in the event dispatching thread. See the link below for more details. private class ButtonListener implements ActionListener{ public void actionperformed(actionevent e) { String input = txtmph.gettext(); if (!isinteger( input ) ) txtfps.settext( "Invalid Input" ); else { int mph = Integer.parseInt( input ); double fps = Convert.mphToFPS( mph ); txtfps.settext( fps + "" ); private boolean isinteger( String s ){ try { int num = Integer.parseInt(s); catch( NumberFormatException ex ) { return false; return true; This is an inner class. It has access to its outer class s instance variables and methods. We use an inner class so that it has access to its outer class s instance variables and methods. It is private because the outer class is the only class that should use this inner class. For an explanation about the code in the display method. 2
3 What is this? jp.setlayout( null ); Java typically uses Layout Manager objects that are responsible for managing the positions and sizes of different components. For example, the GridLayout manager will keep all components the same size and in a grid arrangement even if the frame/panel is resized. Calling the setlayout method with an argument of null means there is no layout manager and we are responsible for positioning everything. Use the setbounds method to position and size any components added to a JPanel. The Coordinate System used by java is similar (but not identical) to the one used in algebra and geometry. -y Each panel has its own coordinate system where the upper-left hand corner is the origin. -x +x The top edge of the panel is the positive x- axis and the left edge of the panel is the positive (not the negative) y-axis. Coordinates can have negative values. +y Here s a figure that shows some of the subclasses of JComponent. Any method that JComponent has, such as setbackground, are inherited by JButton, JPanel, and so on. JComponent AbstractButton JPanel JLabel JTextComponent JButton JTextField 3
4 Ex 1. Create the program that finds the roots of a quadratic equation that is in standard form. The coefficients A, B, and C are all integer values (and assume that the user enters integer values). Complete and use the following class to handle the finding the roots. public class Roots{ public static double [] findroots(int a, int b, int c){ If there are no real roots, return null. If there is only one root, return an array of length 1. If there are two roots, return an array of length 2. Hint. I strongly recommend that you first find the discriminant and then take it from there. Regarding the layout The labels, text fields, and button all have a height of 25 pixels. There is a vertical separation of 5 pixels between each row except around the button where I made the vertical separation a little larger. You don t have to use these numbers in formatting the page. 4
5 Ex 2. This project is a bit more complicated. It is similar to TicTacToe except It is played on a four by four grid. A player must get four in a row (vertically, horizontally, or along one of the two diagonals. IMPORTANT. When a player clicks on their sixth square, the oldest square (the one they clicked on first) will be cleared. No player will ever have more than five marks on the grid at any one time. To be honest, it s not that great a game. Feel free to limit each player to a max of 6 or 7 squares instead of 5 if you think that plays better. Here s an outline of the two classes. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TicTac16_Frame extends JFrame { private JButton[][] btns = new JButton[4][4]; private JButton btnstart = new JButton( "Start" ); private Game16_Logic game = new Game16_Logic(); public static void main(string[] args) { TicTac16_Frame f = new TicTac16_Frame(); f.display(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); public TicTac16_Frame(){ Set up the frame. Create the 17 buttons and place them on the JPanel that is added to the JFrame Change the background color of each button (does not have be orange) setbackground( Color.ORANGE ); Be sure to add listeners to each button. Pay attention to the listener constructor When adding the listener to btnstart, the row and column values do not matter. 5
6 private class ButtonListener implements ActionListener{ private int row, col; public ButtonListener( int r, int c ){ row = r; col = c; public void actionperformed(actionevent e) { JButton b = (JButton) e.getsource(); // useful method if ( b.equals( btnstart ) ){ game.init(); reset the buttons to their original look else if (!game.makemove( row, col ) ) return; // if the move did not occur, then do nothing Call the status method from the Game16_Logic Update all the buttons because two buttons may change with one click You may display Xs and Os or the actual numbers, whichever seems better int [][] results = game.haswinner(); if ( results!= null ) { change the background of the winning buttons to green NOTE. You may want to add helper methods to TicTac16_Frame or ButtonListener. For the game logic, I place odd numbers wherever player one has clicked and even numbers wherever player 2 clicks. At a certain point I remove the smallest even or odd number on the grid (depending on who s turn it is). Also, the player with the smaller value is the next one to make a move. Since I start player1 at 1, player1 is the first one to move. public class Game16_Logic{ private int [][] squares = new int[4][4]; private int player1 = 1; // these are the next values to place private int player2 = 2; private boolean game_on = false; public void init(){ squares = new int[4][4]; player1 = 1; player2 = 2; game_on = true; public int[][] status(){ return squares.clone(); // returns a copy of the grid contents 6
7 public boolean makemove( int row, int col ){ if (!game_on!legalmove( row, col ) ) return false; // indicates that the move was legal if (player1 < player2 ){ if ( player1 > 9 ) // player1 is always odd clearsquare( player1-10 ); squares[row][col] = player1; player1 += 2; else { if ( player2 > 10 ) // player2 is always even clearsquare( player2-10 ); squares[row][col] = player2; player2 += 2; return true; private void clearsquare( int num ){ find the element in the grid that has a value of num and set it to zero private boolean legalmove( int row, int col ){ To return true, (1) row and col must be valid values and (2) squares[row][col] must currently have a value of zero (indicating that the square is unoccupied). Otherwise the method returns false. public int[][] haswinner(){ If there are four square in a row (horizontally, vertically, or diagonally) then return a two-dimensional array containing the locations of these squares. Otherwise return null. You want to use helper methods. 7
8 Simple Animation. Copy and run the following program. This uses a Timer object to generate action events at regular intervals. Explanations for certain statements can be found on the next page. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoTimerFrame extends JFrame { private JLabel lbl = new JLabel( "0" ); private JButton btnstart = new JButton( "Start" ); private JButton btnstop = new JButton( "Stop" ); private JPanel jp = new JPanel(); private int count = 0; private javax.swing.timer timer; A public static void main(string[] args) { DemoTimerFrame f = new DemoTimerFrame(); f.display(); public DemoTimerFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Timer" ); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 150, 150 ) ); jp.setlayout( null ); btnstart.setbounds( 10, 5, 130, 30 ); lbl.setbounds( 60, 50, 90, 30 ); Font f = new Font("SansSerif", Font.BOLD, 36); lbl.setfont( f ); btnstop.setbounds( 10, 100, 130, 30 ); btnstart.addactionlistener( new Respond() ); btnstop.addactionlistener( new Respond() ); B timer = new javax.swing.timer( 100, new TimerListener() ); jp.add( btnstart ); jp.add( lbl ); jp.add( btnstop ); getcontentpane().add( jp ); pack(); C public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); // continued on the next page 8
9 private class TimerListener implements ActionListener { public void actionperformed(actionevent e) { count++; lbl.settext( count + "" ); private class Respond implements ActionListener{ public void actionperformed(actionevent e) { if ( e.getsource().equals( btnstart ) ) timer.start(); else timer.stop(); D E Explanations. A private javax.swing.timer timer; Java has two different Timer classes; one is in the java.util package and one is in the javax.swing package. This syntax makes it clear to the compiler that we want the Timer class from the javax.swing package. We will not use the other Timer class. If you are curious why Java has two Timer classes: B Font f = new Font("SansSerif", Font.BOLD, 36); lbl.setfont( f ); This demonstrates how to change the font type of a JLabel. You could use the same approach on the buttons. Look up the Font class for more information. C new javax.swing.timer( 100, new TimerListener() ); The constructor for the Timer class has two parameters. First, the amount of time, in milliseconds, between events. Second, an object that will respond to the Action Events that a Timer object generates. D private class TimerListener implements ActionListener A Timer object generates Action events at regular intervals therefore the object that responds to those events must implement the ActionListener interface. I used a separate inner class for the timer events because I didn t think the same object should handle action events from buttons and action events from a timer. E timer.start(); timer.stop(); The start method causes the Timer object to start generating action events at the specified interval. The stop method causes the Timer object to stop generating action events. 9
10 Ex 3. This is really cool. You will revise your earlier program so that when the Start Animated Play button is clicked, the computer will randomly click on the buttons until someone one wins. Step 0. Do NOT change Game16_Logic class. Step 1. Copy and rename the TicTac16_Frame. Step 2. Add a timer object with its own private listener class. Every time its actionperformed method is called, randomly select one of the unoccupied squares. Then use this statement: btns[ r ][ c ].doclick(); where r and c are the random row and column that you selected. The doclick event acts the same way as if the user clicked on that button. Step 3. When the Start button is clicked, start the timer. When someone wins, stop the timer. Mouse Events and Drawing on a JPanel. Here is a short demonstrations of how to handle mouse events and draw on a panel. In this example, all the work is being done is a class that extends JPanel. The DemoMouseDrawFrame class is online. It has the main method, creates a frame and adds two DrawMousePanel objects to it. 10
11 import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.arraylist; public class DrawMousePanel extends JPanel { private ArrayList<Point> pts = new ArrayList<Point>(); public DrawMousePanel( Color c ){ setbackground( c ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); setlayout( null ); Mickey m = new Mickey(); addmouselistener( m ); addmousemotionlistener( m public void paintcomponent( Graphics g ){ super.paintcomponent( g ); for ( int k = 0; k < pts.size()-1; k += 2 ){ Point a = pts.get(k); Point b = pts.get(k+1); g.drawline( a.x, a.y, b.x, b.y ); We must call the panel s addmouselistener method so that we can respond when the mouse is pressed on the panel. We must call the panel s addmousemotionlistener method so that we can respond when the mouse is dragged on the panel. The paintcomponent method is called by the JVM whenever (1) the JVM determines that the panel needs to be redrawn or (2) we call the repaint() method. private class Mickey extends MouseAdapter { public void mousepressed( MouseEvent e ){ Point p = new Point( e.getx(), e.gety() ); pts.add( p ); pts.add( p ); // the second point is replaced as the mouse is dragged public void mousedragged( MouseEvent e ){ Point here = new Point( e.getx(), e.gety() ); pts.set( pts.size()-1, here ); repaint(); // causes the JVM to call the paintcomponent method The MouseListener interface has five methods: mousepressed, mousereleased, mouseclicked, mouseentered, mouseexited The MouseMotionListener interface has two methods: mousemoved, mousedragged The MouseAdapter class is an abstract class that implements both of these interfaces. 11
12 Ex 4. Here s how the program should run. - Wherever the user right-clicks on the yellow panel, a bubble appears on the panel and starts moving up. - If the user left-clicks on the bubble, the bubble disappears and they get 5 points. - If the user left-clicks and does not hit any bubble then they lose 5 points. - If a bubble goes off the top of the panel, the score should decrease by 2 points and bubble reappear at the bottom of the panel. There are four classes. The Bubble class encapsulates the idea of a bubble. Each bubble knows its center coordinates, diameter, color, and speed. There is one Bubble constructor: public Bubble( int x, int y ) The parameters initialize the bubbles location. Its speed is random between 5 and 10 (pixels per update). Its diameter is random between 5 and 25 pixels. Its color is random. Red, green, blue, and alpha are all random values between 50 and 150. The Bubble class has five methods: public void draw( Graphics g ) draws itself public boolean contains( int x, int y ) returns true if (x,y) falls within the Bubble; otherwise returns false public Point getlocation() returns the location of its center public void move() moves the Bubble up by whatever its speed is. If the bubble has moved past the top of the field then the score decreases by two and the bubble is moved to the bottom of the field. public void move( int y ) changes the Bubble s y coordinate to the value of the parameter 12
13 The BubbleBath class represents the idea of a collection of bubbles in a field with a specified height. It also has an instance variable to keep score. There is one BubbleBath constructor: public BubbleBath( int h ) The parameter initializes the height of the BubbleBath field. The BubbleBath class has 5 methods public void add( int x, int y ) Adds a bubble centered at this location public boolean check( int x, int y ) Iterates through the collection of bubbles in the field. If the point (x, y) lies within a bubble, that bubble will be deleted and the score increases by 5 points. It is possible that multiple bubbles could be removed if (x, y) lies within multiple overlapping bubbles. If (x, y) does not lie within any bubbles then the score decreases by 5 points. Returns true if at least one bubble was removed; otherwise returns false. public void updatebath() Iterates through the collection of bubbles in the field and calls each bubble s move() method public ArrayList<Bubble> getbubbles() Returns an array list of all the bubbles in the bubble bath. public int getscore() Returns the score The BubblePanel class extends JPanel. It has a BubbleBath object, a reference to its enclosing frame, and a Timer object. There is one BubblePanel constructor: public BubblePanel( Color c, BubbleFrame jf ) { c and f initialize the two corresponding instance variables. Add a mouse listener to the panel Create a timer with a listener start the public void paintcomponent( Graphics g ){ super.paintcomponent( g ); Call BubbleBath s getbubbles method Iterate through the bubbles and call their draw methods There are two inner classes private class Mickey extends MouseAdapter { public void mousepressed( MouseEvent e ){ if ( SwingUtilities.isRightMouseButton( e ) ) { 13
14 Add a bubble to the bubble bath at this location repaint(); else if ( SwingUtilities.isLeftMouseButton( e ) ) { Call the BubbleBath s check method. If it returns true call repaint frame.updatescore( bb.getscore() ); private class TimerListener implements ActionListener { public void actionperformed(actionevent e) { bb.updatebath(); frame.updatescore( bb.getscore() ); repaint(); Finally there is the BubbleFrame class. public class BubbleFrame extends JFrame{ private JLabel lblscore = new JLabel( "Score: 0" ); public static void main(string[] args) { BubbleFrame f = new BubbleFrame(); f.display(); public BubbleFrame(){ Set up the frame that contains one JPanel Create a BubblePanel and add that to the main JPanel Add the JLabel to the main JPanel public void updatescore( int num ){ lblscore.settext( "Score: " + num ); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); 14
AP CS Unit 11: Graphics and Events
AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two
More informationAP CS Unit 12: Drawing and Mouse Events
AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that.
More informationAP Computer Science Unit 13. Still More Graphics and Animation.
AP Computer Science Unit 13. Still More Graphics and Animation. In this unit you ll learn about the following: Mouse Motion Listener Suggestions for designing better graphical programs Simple game with
More informationOutline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics
Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming
More informationFrames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling
Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)
More informationG51PRG: Introduction to Programming Second semester Applets and graphics
G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting
More informationPIC 20A GUI with swing
PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args
More informationProgrammierpraktikum
Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications
More informationPROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7
PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,
More informationCommand-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.
1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is
More informationClass 16: The Swing Event Model
Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #19: November 4, 2015 1/14 Third Exam The third, Checkpoint Exam, will be on: Wednesday, November 11, 2:30 to 3:45 pm You will have 3 questions, out of 9,
More informationLecture 5: Java Graphics
Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,
More informationUnit 7: Event driven programming
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.
More informationRAIK 183H Examination 2 Solution. November 10, 2014
RAIK 183H Examination 2 Solution November 10, 2014 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)
More information2. (True/False) All methods in an interface must be declared public.
Object and Classes 1. Create a class Rectangle that represents a rectangular region of the plane. A rectangle should be described using four integers: two represent the coordinates of the upper left corner
More informationStarting Out with Java: From Control Structures Through Objects Sixth Edition
Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes
More information(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI
51 6!! GUI(Graphical User Interface) java.awt javax.swing (component) GUI... (container) (listener)... MouseListener, ActionLister (adapter)... MouseAdapter, ActionAdapter 6.1 GUI(Graphics User Interface
More informationGUI DYNAMICS Lecture July 26 CS2110 Summer 2011
GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: Standard Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More information2IS45 Programming
Course Website Assignment Goals 2IS45 Programming http://www.win.tue.nl/~wsinswan/programmeren_2is45/ Rectangles Learn to use existing Abstract Data Types based on their contract (class Rectangle in Rectangle.
More informationJava Programming Lecture 6
Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components
More informationLecture 3: Java Graphics & Events
Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new
More informationQueen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb
Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb HAND IN Answers recorded on Examination paper This examination is THREE HOURS
More informationThe JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class
CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical
More informationpublic void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety();
11 The Jav aawt Part I: Mouse Events 11.1 public void mouseentered (MouseEvent e) setminute(getminute()+increment); 53 public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public
More informationTopic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more
Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"
More informationTopic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!
Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques
More informationOOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:
OOP Assignment V If we don t use multithreading, or a timer, and update the contents of the applet continuously by calling the repaint() method, the processor has to update frames at a blinding rate. Too
More informationMIT AITI Swing Event Model Lecture 17
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 user. But how do GUIs interact with users? How do applications
More informationG51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread
G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals
More informationPart I: Learn Common Graphics Components
OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect
More informationLecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:
Lecture 28 Exceptions and Inner Classes Goals We are going to talk in more detail about two advanced Java features: Exceptions supply Java s error handling mechanism. Inner classes ease the overhead of
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More informationVirtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.
1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program
More informationFirstSwingFrame.java Page 1 of 1
FirstSwingFrame.java Page 1 of 1 2: * A first example of using Swing. A JFrame is created with 3: * a label and buttons (which don t yet respond to events). 4: * 5: * @author Andrew Vardy 6: */ 7: import
More informationRAIK 183H Examination 2 Solution. November 11, 2013
RAIK 183H Examination 2 Solution November 11, 2013 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)
More informationIntroduction This assignment will ask that you write a simple graphical user interface (GUI).
Computing and Information Systems/Creative Computing University of London International Programmes 2910220: Graphical Object-Oriented and Internet programming in Java Coursework one 2011-12 Introduction
More informationCSIS 10A Assignment 14 SOLUTIONS
CSIS 10A Assignment 14 SOLUTIONS Read: Chapter 14 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,
More informationJava: Graphical User Interfaces (GUI)
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 32 April 9, 2018 Swing I: Drawing and Event Handling Chapter 29 HW8: Spellchecker Available on the web site Due: Tuesday! Announcements Parsing, working
More informationName: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.
Lab 15 Name: Checked: Objectives: Learn about listeners, events, and simple animation for interactive graphical user interfaces. Files: http://www.csc.villanova.edu/~map/1051/chap04/smilingface.java http://www.csc.villanova.edu/~map/1051/chap04/smilingfacepanel.java
More informationDatenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1
Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1 Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text
More informationUser interfaces and Swing
User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends
More informationCSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT
CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/
More informationHanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS
Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Glossary of Terms 2-4 Step by Step Instructions 4-7 HWApp 8 HWFrame 9 Never trust a computer
More informationCSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction
CSC 160 LAB 8-1 DIGITAL PICTURE FRAME PROFESSOR GODFREY MUGANDA DEPARTMENT OF COMPUTER SCIENCE 1. Introduction Download and unzip the images folder from the course website. The folder contains 28 images
More informationWindow Interfaces Using Swing Objects
Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs
More informationJava Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing
Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/
More informationGraphical User Interface (GUI)
Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware
More informationSINGLE EVENT HANDLING
SINGLE EVENT HANDLING Event handling is the process of responding to asynchronous events as they occur during the program run. An event is an action that occurs externally to your program and to which
More informationGraphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)
Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build
More informationEXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal
Review Session for EXCEPTIONS & GUI -Ankur Agarwal An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Errors are signals
More informationPackages: Putting Classes Together
Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic
More informationGraphical User Interfaces 2
Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Overview
More informationEvent Driven Programming
Event Driven Programming 1. Objectives... 2 2. Definitions... 2 3. Event-Driven Style of Programming... 2 4. Event Polling Model... 3 5. Java's Event Delegation Model... 5 6. How to Implement an Event
More informationIntroduction to the JAVA UI classes Advanced HCI IAT351
Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing
More informationClass 27: Nested Classes and an Introduction to Trees
Introduction to Computation and Problem Solving Class 27: Nested Classes and an Introduction to Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To explain in more detail the different types
More informationCome & Join Us at VUSTUDENTS.net
Come & Join Us at VUSTUDENTS.net For Assignment Solution, GDB, Online Quizzes, Helping Study material, Past Solved Papers, Solved MCQs, Current Papers, E-Books & more. Go to http://www.vustudents.net and
More informationWindow Interfaces Using Swing Objects
Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs
More informationCSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1 The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous
More informationIntroduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008
Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Announcements A3 is up, due Friday, Oct 10 Prelim 1 scheduled for Oct 16 if you have a conflict, let us know now 2 Interactive
More informationCS11 Java. Fall Lecture 3
CS11 Java Fall 2014-2015 Lecture 3 Today s Topics! Class inheritance! Abstract classes! Polymorphism! Introduction to Swing API and event-handling! Nested and inner classes Class Inheritance! A third of
More informationCS 170 Java Programming 1. Week 9: Learning about Loops
CS 170 Java Programming 1 Week 9: Learning about Loops What s the Plan? Topic 1: A Little Review ACM GUI Apps, Buttons, Text and Events Topic 2: Learning about Loops Different kinds of loops Using loops
More informationCS 251 Intermediate Programming GUIs: Components and Layout
CS 251 Intermediate Programming GUIs: Components and Layout Brooke Chenoweth University of New Mexico Fall 2017 import javax. swing.*; Hello GUI public class HelloGUI extends JFrame { public HelloGUI ()
More informationControl Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User
CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by
More informationCS 251 Intermediate Programming GUIs: Event Listeners
CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener
More informationLecture 19 GUI Events
CSE 331 Software Design and Implementation Lecture 19 GUI Events The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction
More informationLab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!
Lab & Assignment 1 Lecture 3: ArrayList & Standard Java Graphics CS 62 Fall 2015 Kim Bruce & Michael Bannister Strip with 12 squares & 5 silver dollars placed randomly on the board. Move silver dollars
More informationCS2110. GUIS: Listening to Events
CS2110. GUIS: Listening to Events Also anonymous classes Download the demo zip file from course website and look at the demos of GUI things: sliders, scroll bars, combobox listener, etc 1 mainbox boardbox
More informationCOMP Assignment #10 (Due: Monday, March 11:30pm)
COMP1406 - Assignment #10 (Due: Monday, March 31st @ 11:30pm) In this assignment you will practice using recursion with data structures. (1) Consider the following BinaryTree class: public class BinaryTree
More informationOBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613
OBJECT ORIENTED PROGRAMMING Course 8 Loredana STANCIU loredana.stanciu@upt.ro Room B613 Applets A program written in the Java programming language that can be included in an HTML page A special kind of
More information17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau
List of Slides 1 Title 2 Chapter 13: Graphical user interfaces 3 Chapter aims 4 Section 2: Example:Hello world with a GUI 5 Aim 6 Hello world with a GUI 7 Hello world with a GUI 8 Package: java.awt and
More informationCS108, Stanford Handout #22. Thread 3 GUI
CS108, Stanford Handout #22 Winter, 2006-07 Nick Parlante Thread 3 GUI GUIs and Threading Problem: Swing vs. Threads How to integrate the Swing/GUI/drawing system with threads? Problem: The GUI system
More informationKF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation
KF5008 Program Design & Development Lecture 1 Usability GUI Design and Implementation Types of Requirements Functional Requirements What the system does or is expected to do Non-functional Requirements
More informationSwing from A to Z Some Simple Components. Preface
By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments
More informationCOMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )
COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) ) Course Evaluations Please do these. -Fast to do -Used to
More informationJava. GUI building with the AWT
Java GUI building with the AWT AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses the controls defined by your OS therefore
More informationCSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing
CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic
More informationHW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.
HW#1: Pencil Me In Status!? CS193J: Programming in Java Summer Quarter 2003 Lecture 6 Inner Classes, Listeners, Repaint Manu Kumar sneaker@stanford.edu How was Homework #1? Comments please? SITN students
More informationAssignment 2. Application Development
Application Development Assignment 2 Content Application Development Day 2 Lecture The lecture covers the key language elements of the Java programming language. You are introduced to numerical data and
More informationPart 3: Graphical User Interface (GUI) & Java Applets
1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ
More informationUI Software Organization
UI Software Organization The user interface From previous class: Generally want to think of the UI as only one component of the system Deals with the user Separate from the functional core (AKA, the app
More informationHeavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.
Java GUI Windows Events Drawing 1 Java GUI Toolkits Toolkit AWT Description Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.
More informationInheritance. One class inherits from another if it describes a specialized subset of objects Terminology:
Inheritance 1 Inheritance One class inherits from another if it describes a specialized subset of objects Terminology: the class that inherits is called a child class or subclass the class that is inherited
More informationCS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM
CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM Introduction to the Assignment In this assignment, you will get practice with recursion. There are three parts
More informationBASICS OF GRAPHICAL APPS
CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In
More informationPractice Midterm 1. Problem Points Score TOTAL 50
CS 120 Software Design I Spring 2019 Practice Midterm 1 University of Wisconsin - La Crosse February 25 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages including the
More informationAn array is a type of variable that is able to hold more than one piece of information under a single variable name.
Arrays An array is a type of variable that is able to hold more than one piece of information under a single variable name. Basically you are sub-dividing a memory box into many numbered slots that can
More informationProgramming graphics
Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it
More informationBuilding a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver
Building a GUI in Java with Swing CITS1001 extension notes Rachel Cardell-Oliver Lecture Outline 1. Swing components 2. Building a GUI 3. Animating the GUI 2 Swing A collection of classes of GUI components
More informationGraphical interfaces & event-driven programming
Graphical interfaces & event-driven programming Lecture 12 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 Pop quiz!
More informationCourse Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski
CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule
More informationCS11 Java. Fall Lecture 4
CS11 Java Fall 2006-2007 Lecture 4 Today s Topics Interfaces The Swing API Event Handlers Inner Classes Arrays Java Interfaces Classes can only have one parent class No multiple inheritance in Java! By
More informationSE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts
SE1021 Exam 2 Name: You may use a note-sheet for this exam. But all answers should be your own, not from slides or text. Review all questions before you get started. The exam is printed single-sided. Write
More informationWhat Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }
CBOP3203 What Is an Event? Events Objects that describe what happened Event Sources The generator of an event Event Handlers A method that receives an event object, deciphers it, and processes the user
More information11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events
Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes
More informationGraphic User Interfaces. - GUI concepts - Swing - AWT
Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations
More informationGraphical User Interface (GUI)
Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware
More information1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2
1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring 2010 - Quiz 2 Name: MIT Email: TA: Section: You have 80 minutes to complete this exam. For coding questions, you do not need
More information