SlideShare a Scribd company logo
1 of 23
Download to read offline
Frame Class
Lecture 10
Naveen Kumar
A Simple Program
import javax.swing.JFrame;
import javax.swing.JLabel;
HelloWorldFrame extends Jframe
{
public static void main(String args[])
{ JFrame f = new JFrame();
f. setSize(100, 100);
JLabel X = new JLabel("Hello World");
f.add(X);
f.setVisible(true);
} }
2
A Simple Program
import javax.swing.JFrame;
import javax.swing.JLabel;
HelloWorldFrame extends Jframe
{
public static void main(String args[])
{ new HelloWorldFrame();
}
HelloWorldFrame()
{ JLabel X = new JLabel("Hello World");
add(X);
setSize(100, 100);
setVisible(true);
} }3
Problem: on window close cursor will not go
on C: prompt
Frame Windows
 The JFrame class JFrame frame = new JFrame();
 frame.setSize(300, 400);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
 import javax.swing.*;
4
Frame program
import javax.swing.*;
public class frame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
5
Self Check
 How do you display a square frame with a title bar that
reads "Hello, World!"?
 How can a program display two frames at once?
Answers
 Modify the EmptyFrameViewer program as follows:
frame.setSize(300, 300);
frame.setTitle("Hello, World!");
 Construct two JFrame objects, set each of their sizes,
and call setVisible(true) on each of them
6
Drawing Shapes
 paintComponent: called whenever the component
needs to be repainted:
public class frame1 extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
. . .
}
}
7
Drawing Shapes
 Graphics class lets you manipulate the graphics state
(such as current color)
 Graphics2D class has methods to draw shape objects
 Use a cast to recover the Graphics2D object from the
Graphics parameter
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
 java.awt package8
Rectangle Drawing Program Classes
 frame1: its paintComponent method produces the drawing
 frame: its main method constructs a frame and a frame1, adds the
component to the frame, and makes the frame visible
– Construct a frame
– Construct an object of your component class:
frame1 component = new frame1();
– Add the component to the frame
frame.add(component);
However, if you use an older version of Java (before Version 5), you
must make a slightly more complicated call:
frame.getContentPane().add(component);
– Make the frame visible frame.setVisible(true);
9
An example (produce a drawing
with two boxes)
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent; /** A component that draws two rectangles. */
public class frame1 extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; // Recover Graphics2D
Rectangle box = new Rectangle(5, 10, 20, 30); // Construct a rectangle and
g2.draw(box); // draw it
box.translate(15, 25); // Move rectangle 15 units to the right and 25 units down
g2.draw(box); // Draw moved rectangle
} }
10
Create frame and add drawing
import javax.swing.JFrame;
public class frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setTitle("Two rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1 component = new frame1();
frame.add(component);
frame.setVisible(true);
} }11
Self Check
 How do you modify the program to draw two squares?
 How do you modify the program to draw one rectangle and one
square?
 What happens if you call g.draw(box) instead of g2.draw(box)?
Answers
 Rectangle box = new Rectangle(5, 10, 20, 20);
 Replace the call to box.translate(15, 25) with
box = new Rectangle(20, 35, 20, 20);
 The compiler complains that g doesn't have a draw method
12
Applets
 This is almost the same outline as for a component, with two minor
differences:
– You extend JApplet, not JComponent
– You place the drawing code inside the paint method, not inside
paintComponent
 To run an applet, you need an HTML file with the applet tag
 You view applets with the appletviewer
13
JApplet
/* <APPLET CODE="frameapplet.class" WIDTH=350 HEIGHT=200>
</APPLET>*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JApplet; /** An applet that draws two rectangles. */
public class frameapplet extends JApplet
{ public void paint(Graphics g)
{ // Prepare for extended graphics
Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box); // Move rectangle 15 units to the right and 25 units down
box.translate(15, 25); // Draw moved rectangle
g2.draw(box);
} }
14
Graphical Shapes
 Rectangle, Ellipse2D.Double, and Line2D.Double describe graphical
shapes
 We won't use the .Float classes
 These classes are inner classes–doesn't matter to us except for the
import statement:
import java.awt.geom.Ellipse2D; // no .Double
 Must construct and draw the shape
Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);
g2.draw(ellipse);
15
Drawing Lines
To draw a line:
 Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2);
or
 Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double segment = new Line2D.Double(from, to);
16
Self Check
 Give instructions to draw a circle with center (100,100) and radius 25
 Give instructions to draw a letter "V" by drawing two line segments
 Give instructions to draw a string consisting of the letter "V"
Answers
 g2.draw(new Ellipse2D.Double(75, 75, 50, 50);
 Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30);
g2.draw(segment1);
Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0);
g2.draw(segment2);
 g2.drawString("V", 0, 30);
17
Upper-left corner, Width , Height
Colors
 Standard colors Color.BLUE, Color.RED, Color.PINK etc.
 Specify red, green, blue between 0.0F and 1.0F
 Color magenta = new Color(1.0F, 0.0F, 1.0F); // F = float
Set color in graphics context
 g2.setColor(magenta);
Color is used when drawing and filling shapes
 g2.fill(rectangle); // filled with current color
18
Self Check
 What are the RGB color values of Color.BLUE?
 How do you draw a yellow square on a red background?
Answers
 0.0F, 0.0F, and 0.1F
 First fill a big red square, then fill a small yellow square inside:
g2.setColor(Color.RED);
g2.fill(new Rectangle(0, 0, 200, 200));
g2.setColor(Color.YELLOW);
g2.fill(new Rectangle(50, 50, 100, 100));
Note: Use import java.awt.Color;
19
Drawing Graphical Shapes
 Rectangle leftRectangle
= new Rectangle(100, 100, 30, 60);
Rectangle rightRectangle
= new Rectangle(160, 100, 30, 60);
Line2D.Double topLine
= new Line2D.Double(130, 100, 160, 100);
Line2D.Double bottomLine
= new Line2D.Double(130, 160, 160, 160);
20
Reading Text Input
 A graphical application can obtain input by displaying a
JOptionPane
 The showInputDialog method displays a prompt and
waits for user input
 The showInputDialog method returns the string that the
user typed
String input = JOptionPane.showInputDialog("Enter x");
double x = Double.parseDouble(input);
21
An Example
import java.awt.Color; import javax.swing.Jframe;
import javax.swing.JOptionPane; import javax.swing.JComponent;
public class ColorViewer {
public static void main(String[] args) {
JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String input; // Ask the user for red, green, blue values
input = JOptionPane.showInputDialog("red:");
double red = Double.parseDouble(input);
input = JOptionPane.showInputDialog("green:");
double green = Double.parseDouble(input);
input = JOptionPane.showInputDialog("blue:");
double blue = Double.parseDouble(input);
Color fillColor = new Color( (float) red, (float) green, (float) blue);
Square component = new Square (fillColor);
frame.add(component); frame.setVisible(true); } }22
Example cont.
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle
public class Square extends Jcomponent {
private Color fillColor;
public Square (Color aColor) { fillColor = aColor; }
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; // Select color into graphics context
g2.setColor(fillColor); // Const and fill a square whose center is center of the window
Rectangle square = new Rectangle(20,40,100,100);
g2.fill(square); }
}
23

More Related Content

What's hot

Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 

What's hot (20)

Aspect-Oriented Technologies
Aspect-Oriented TechnologiesAspect-Oriented Technologies
Aspect-Oriented Technologies
 
Implementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChartImplementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChart
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
 
OpenVX 1.0 Reference Guide
OpenVX 1.0 Reference GuideOpenVX 1.0 Reference Guide
OpenVX 1.0 Reference Guide
 
OpenVX 1.3 Reference Guide
OpenVX 1.3 Reference GuideOpenVX 1.3 Reference Guide
OpenVX 1.3 Reference Guide
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
java graphics
java graphicsjava graphics
java graphics
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
1z0 851 exam-java standard edition 6 programmer certified professional
1z0 851 exam-java standard edition 6 programmer certified professional1z0 851 exam-java standard edition 6 programmer certified professional
1z0 851 exam-java standard edition 6 programmer certified professional
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
MVC meets Monad
MVC meets MonadMVC meets Monad
MVC meets Monad
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
 
Implementasi Pemodelan Sistem Ke TeeChart 2
Implementasi Pemodelan Sistem Ke TeeChart  2Implementasi Pemodelan Sistem Ke TeeChart  2
Implementasi Pemodelan Sistem Ke TeeChart 2
 
Intro to Matlab programming
Intro to Matlab programmingIntro to Matlab programming
Intro to Matlab programming
 
Grokking Monads in Scala
Grokking Monads in ScalaGrokking Monads in Scala
Grokking Monads in Scala
 
Isc computer project final upload last
Isc computer project final upload lastIsc computer project final upload last
Isc computer project final upload last
 
Cgm Lab Manual
Cgm Lab ManualCgm Lab Manual
Cgm Lab Manual
 

Similar to Lec 10 10_sept [compatibility mode]

This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
anjandavid
 
HELPModify the code so that the ListItem contains two values, inst.pdf
HELPModify the code so that the ListItem contains two values, inst.pdfHELPModify the code so that the ListItem contains two values, inst.pdf
HELPModify the code so that the ListItem contains two values, inst.pdf
monikajain201
 
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfImport java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
apexcomputer54
 
Please read this carefully needs to be in JAVA        Java 2D intr.pdf
Please read this carefully needs to be in JAVA        Java 2D intr.pdfPlease read this carefully needs to be in JAVA        Java 2D intr.pdf
Please read this carefully needs to be in JAVA        Java 2D intr.pdf
PRATIKSINHA7304
 
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdfJEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
MarlouFelixIIICunana
 
Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
JUSTSTYLISH3B2MOHALI
 
Task Write a Java program to implement a simple graphics editor tha.pdf
Task Write a Java program to implement a simple graphics editor tha.pdfTask Write a Java program to implement a simple graphics editor tha.pdf
Task Write a Java program to implement a simple graphics editor tha.pdf
cronkwurphyb44502
 
draw a pikachu in java package arreyreview- import java-awt--- import.pdf
draw a pikachu in java package arreyreview- import java-awt--- import.pdfdraw a pikachu in java package arreyreview- import java-awt--- import.pdf
draw a pikachu in java package arreyreview- import java-awt--- import.pdf
Jake3sTAveryn
 

Similar to Lec 10 10_sept [compatibility mode] (20)

This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
 
HELPModify the code so that the ListItem contains two values, inst.pdf
HELPModify the code so that the ListItem contains two values, inst.pdfHELPModify the code so that the ListItem contains two values, inst.pdf
HELPModify the code so that the ListItem contains two values, inst.pdf
 
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfImport java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
 
explain how 2D drawing is done in Java using Swing- Have you done this.docx
explain how 2D drawing is done in Java using Swing- Have you done this.docxexplain how 2D drawing is done in Java using Swing- Have you done this.docx
explain how 2D drawing is done in Java using Swing- Have you done this.docx
 
662305 LAB13
662305 LAB13662305 LAB13
662305 LAB13
 
662305 11
662305 11662305 11
662305 11
 
write a prgoram that displays four images or objects in a 2 x 2 grid.pdf
write a prgoram that displays four images or objects in a 2 x 2 grid.pdfwrite a prgoram that displays four images or objects in a 2 x 2 grid.pdf
write a prgoram that displays four images or objects in a 2 x 2 grid.pdf
 
Please read this carefully needs to be in JAVA        Java 2D intr.pdf
Please read this carefully needs to be in JAVA        Java 2D intr.pdfPlease read this carefully needs to be in JAVA        Java 2D intr.pdf
Please read this carefully needs to be in JAVA        Java 2D intr.pdf
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
Learn Java 3D
Learn Java 3D Learn Java 3D
Learn Java 3D
 
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdfJEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعةشرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
10java 2d
10java 2d10java 2d
10java 2d
 
Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Task Write a Java program to implement a simple graphics editor tha.pdf
Task Write a Java program to implement a simple graphics editor tha.pdfTask Write a Java program to implement a simple graphics editor tha.pdf
Task Write a Java program to implement a simple graphics editor tha.pdf
 
This code currently works... Run it and get a screen shot of its .docx
 This code currently works... Run it and get a screen shot of its .docx This code currently works... Run it and get a screen shot of its .docx
This code currently works... Run it and get a screen shot of its .docx
 
draw a pikachu in java package arreyreview- import java-awt--- import.pdf
draw a pikachu in java package arreyreview- import java-awt--- import.pdfdraw a pikachu in java package arreyreview- import java-awt--- import.pdf
draw a pikachu in java package arreyreview- import java-awt--- import.pdf
 

More from Palak Sanghani

More from Palak Sanghani (20)

Survey form
Survey formSurvey form
Survey form
 
Survey
SurveySurvey
Survey
 
Nature2
Nature2Nature2
Nature2
 
Texture
TextureTexture
Texture
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]
 
Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
Lec 2 30_jul13
Lec 2 30_jul13Lec 2 30_jul13
Lec 2 30_jul13
 
Lec 1 25_jul13
Lec 1 25_jul13Lec 1 25_jul13
Lec 1 25_jul13
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Nature
NatureNature
Nature
 
Comparisionof trees
Comparisionof treesComparisionof trees
Comparisionof trees
 
My Structure Patterns
My Structure PatternsMy Structure Patterns
My Structure Patterns
 
My Similarity Patterns
My Similarity PatternsMy Similarity Patterns
My Similarity Patterns
 
My Radiation Patterns
My Radiation PatternsMy Radiation Patterns
My Radiation Patterns
 
My Gradation Patterns
My Gradation PatternsMy Gradation Patterns
My Gradation Patterns
 
My Circular Patterns
My Circular PatternsMy Circular Patterns
My Circular Patterns
 
My Anomaly Patterns
My Anomaly PatternsMy Anomaly Patterns
My Anomaly Patterns
 
Library of Babel Illustrations
Library of Babel IllustrationsLibrary of Babel Illustrations
Library of Babel Illustrations
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Lec 10 10_sept [compatibility mode]

  • 2. A Simple Program import javax.swing.JFrame; import javax.swing.JLabel; HelloWorldFrame extends Jframe { public static void main(String args[]) { JFrame f = new JFrame(); f. setSize(100, 100); JLabel X = new JLabel("Hello World"); f.add(X); f.setVisible(true); } } 2
  • 3. A Simple Program import javax.swing.JFrame; import javax.swing.JLabel; HelloWorldFrame extends Jframe { public static void main(String args[]) { new HelloWorldFrame(); } HelloWorldFrame() { JLabel X = new JLabel("Hello World"); add(X); setSize(100, 100); setVisible(true); } }3 Problem: on window close cursor will not go on C: prompt
  • 4. Frame Windows  The JFrame class JFrame frame = new JFrame();  frame.setSize(300, 400); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);  import javax.swing.*; 4
  • 5. Frame program import javax.swing.*; public class frame { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } 5
  • 6. Self Check  How do you display a square frame with a title bar that reads "Hello, World!"?  How can a program display two frames at once? Answers  Modify the EmptyFrameViewer program as follows: frame.setSize(300, 300); frame.setTitle("Hello, World!");  Construct two JFrame objects, set each of their sizes, and call setVisible(true) on each of them 6
  • 7. Drawing Shapes  paintComponent: called whenever the component needs to be repainted: public class frame1 extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } } 7
  • 8. Drawing Shapes  Graphics class lets you manipulate the graphics state (such as current color)  Graphics2D class has methods to draw shape objects  Use a cast to recover the Graphics2D object from the Graphics parameter Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box);  java.awt package8
  • 9. Rectangle Drawing Program Classes  frame1: its paintComponent method produces the drawing  frame: its main method constructs a frame and a frame1, adds the component to the frame, and makes the frame visible – Construct a frame – Construct an object of your component class: frame1 component = new frame1(); – Add the component to the frame frame.add(component); However, if you use an older version of Java (before Version 5), you must make a slightly more complicated call: frame.getContentPane().add(component); – Make the frame visible frame.setVisible(true); 9
  • 10. An example (produce a drawing with two boxes) import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; /** A component that draws two rectangles. */ public class frame1 extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Recover Graphics2D Rectangle box = new Rectangle(5, 10, 20, 30); // Construct a rectangle and g2.draw(box); // draw it box.translate(15, 25); // Move rectangle 15 units to the right and 25 units down g2.draw(box); // Draw moved rectangle } } 10
  • 11. Create frame and add drawing import javax.swing.JFrame; public class frame { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH,FRAME_HEIGHT); frame.setTitle("Two rectangles"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1 component = new frame1(); frame.add(component); frame.setVisible(true); } }11
  • 12. Self Check  How do you modify the program to draw two squares?  How do you modify the program to draw one rectangle and one square?  What happens if you call g.draw(box) instead of g2.draw(box)? Answers  Rectangle box = new Rectangle(5, 10, 20, 20);  Replace the call to box.translate(15, 25) with box = new Rectangle(20, 35, 20, 20);  The compiler complains that g doesn't have a draw method 12
  • 13. Applets  This is almost the same outline as for a component, with two minor differences: – You extend JApplet, not JComponent – You place the drawing code inside the paint method, not inside paintComponent  To run an applet, you need an HTML file with the applet tag  You view applets with the appletviewer 13
  • 14. JApplet /* <APPLET CODE="frameapplet.class" WIDTH=350 HEIGHT=200> </APPLET>*/ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JApplet; /** An applet that draws two rectangles. */ public class frameapplet extends JApplet { public void paint(Graphics g) { // Prepare for extended graphics Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); // Move rectangle 15 units to the right and 25 units down box.translate(15, 25); // Draw moved rectangle g2.draw(box); } } 14
  • 15. Graphical Shapes  Rectangle, Ellipse2D.Double, and Line2D.Double describe graphical shapes  We won't use the .Float classes  These classes are inner classes–doesn't matter to us except for the import statement: import java.awt.geom.Ellipse2D; // no .Double  Must construct and draw the shape Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height); g2.draw(ellipse); 15
  • 16. Drawing Lines To draw a line:  Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); or  Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to); 16
  • 17. Self Check  Give instructions to draw a circle with center (100,100) and radius 25  Give instructions to draw a letter "V" by drawing two line segments  Give instructions to draw a string consisting of the letter "V" Answers  g2.draw(new Ellipse2D.Double(75, 75, 50, 50);  Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30); g2.draw(segment1); Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0); g2.draw(segment2);  g2.drawString("V", 0, 30); 17 Upper-left corner, Width , Height
  • 18. Colors  Standard colors Color.BLUE, Color.RED, Color.PINK etc.  Specify red, green, blue between 0.0F and 1.0F  Color magenta = new Color(1.0F, 0.0F, 1.0F); // F = float Set color in graphics context  g2.setColor(magenta); Color is used when drawing and filling shapes  g2.fill(rectangle); // filled with current color 18
  • 19. Self Check  What are the RGB color values of Color.BLUE?  How do you draw a yellow square on a red background? Answers  0.0F, 0.0F, and 0.1F  First fill a big red square, then fill a small yellow square inside: g2.setColor(Color.RED); g2.fill(new Rectangle(0, 0, 200, 200)); g2.setColor(Color.YELLOW); g2.fill(new Rectangle(50, 50, 100, 100)); Note: Use import java.awt.Color; 19
  • 20. Drawing Graphical Shapes  Rectangle leftRectangle = new Rectangle(100, 100, 30, 60); Rectangle rightRectangle = new Rectangle(160, 100, 30, 60); Line2D.Double topLine = new Line2D.Double(130, 100, 160, 100); Line2D.Double bottomLine = new Line2D.Double(130, 160, 160, 160); 20
  • 21. Reading Text Input  A graphical application can obtain input by displaying a JOptionPane  The showInputDialog method displays a prompt and waits for user input  The showInputDialog method returns the string that the user typed String input = JOptionPane.showInputDialog("Enter x"); double x = Double.parseDouble(input); 21
  • 22. An Example import java.awt.Color; import javax.swing.Jframe; import javax.swing.JOptionPane; import javax.swing.JComponent; public class ColorViewer { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String input; // Ask the user for red, green, blue values input = JOptionPane.showInputDialog("red:"); double red = Double.parseDouble(input); input = JOptionPane.showInputDialog("green:"); double green = Double.parseDouble(input); input = JOptionPane.showInputDialog("blue:"); double blue = Double.parseDouble(input); Color fillColor = new Color( (float) red, (float) green, (float) blue); Square component = new Square (fillColor); frame.add(component); frame.setVisible(true); } }22
  • 23. Example cont. import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle public class Square extends Jcomponent { private Color fillColor; public Square (Color aColor) { fillColor = aColor; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Select color into graphics context g2.setColor(fillColor); // Const and fill a square whose center is center of the window Rectangle square = new Rectangle(20,40,100,100); g2.fill(square); } } 23