SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Java Data types and Variables
Lecture 7
Naveen Kumar
Strings
 A string is a sequence of characters
 Strings are objects of the String class
 String constants:
"Hello, World!"
 String variables:
String message = "Hello, World!";
 String length:
int n = message.length();
 Empty string: ""
2
Concatenation
 Use the + operator:
String name = "Dave";
String message = "Hello, " + name;
// message is "Hello, Dave"
 If one of the arguments of the + operator is a
string, the other is converted to a string
String a = "Agent";
int n = 7;
String bond = a + n; // bond is Agent7
3
Converting between Strings and
Numbers
 Convert to number:
int n = Integer.parseInt(str);
double x = Double.parseDouble(x);
int num = Integer.parseInt("1234");
 Convert to string:
String str = "" + n;
str = Integer.toString(n);
String str = String.valueOf(num);4
Substrings
 String greeting = "Hello, World!";
String sub = greeting.substring(0, 5);
// sub is "Hello"
 Supply start and end positions, end is not
included
 First position is at 0
5
Self Check
 Assuming the String variable s holds the value "Agent", what is
the effect of the assignment s = s + s.length() ?
 Assuming the String variable river holds the value "Mississippi",
what is the value of
river.substring(1, 2)? and
river.substring(2, river.length() - 3)?
Answers
 s is set to the string Agent5
 The strings "i" and
 "ssissi"
6
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.*;
7
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);
}
}
8
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
9
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;
. . .
}
}
10
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 package11
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
12
An example (produce a drawing
with two boxes)
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JPanel;
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
} }
13
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);
} }14
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
15
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
16
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);
}
}
17
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);
18
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);
19
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);
20
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
21
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;
22
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);
23
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);
24
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);
ColoredSquarecomponent = new ColoredSquare (fillColor);
frame.add(component); frame.setVisible(true); } }25
Example cont.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D;
import java.awt.Rectangle; import javax.swing.JComponent;
public class ColoredSquare extends Jcomponent {
private Color fillColor;
public ColoredSquare (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
final int SQUARE_LENGTH = 100;
Rectangle square = new Rectangle((getWidth() - SQUARE_LENGTH) / 2, (getHeight()
SQUARE_LENGTH) / 2, SQUARE_LENGTH, SQUARE_LENGTH);
g2.fill(square); }
}26

Weitere ähnliche Inhalte

Was ist angesagt?

June 05 P2
June 05 P2June 05 P2
June 05 P2
Samimvez
 

Was ist angesagt? (16)

Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
 
Introduction to graphics programming in c
Introduction to graphics programming in cIntroduction to graphics programming in c
Introduction to graphics programming in c
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Tutorial 2
Tutorial     2Tutorial     2
Tutorial 2
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
Computer Graphics Lab
Computer Graphics LabComputer Graphics Lab
Computer Graphics Lab
 
OpenGL 4.4 Reference Card
OpenGL 4.4 Reference CardOpenGL 4.4 Reference Card
OpenGL 4.4 Reference Card
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
June 05 P2
June 05 P2June 05 P2
June 05 P2
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
 
Applications
ApplicationsApplications
Applications
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Andere mochten auch (9)

Film treatment new 2011.j.e.sdocx
Film treatment new 2011.j.e.sdocxFilm treatment new 2011.j.e.sdocx
Film treatment new 2011.j.e.sdocx
 
One Source Solution
One Source SolutionOne Source Solution
One Source Solution
 
Pertemuan 4 ok
Pertemuan 4 okPertemuan 4 ok
Pertemuan 4 ok
 
Apuntes acidos nucleicos
Apuntes acidos nucleicosApuntes acidos nucleicos
Apuntes acidos nucleicos
 
Seleksi tofi 1997 soal
Seleksi tofi 1997 soalSeleksi tofi 1997 soal
Seleksi tofi 1997 soal
 
Seleksi tofi 2000 soal
Seleksi tofi 2000 soalSeleksi tofi 2000 soal
Seleksi tofi 2000 soal
 
Em research
Em researchEm research
Em research
 
Quantum hall effect
Quantum hall effectQuantum hall effect
Quantum hall effect
 
3. vibration and waves
3. vibration and waves3. vibration and waves
3. vibration and waves
 

Ähnlich wie Lec 7 28_aug [compatibility mode]

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
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
tutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
tutorialsruby
 
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdfimport java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
anyacarpets
 
C# I need assitance on my code.. Im getting an error message Us.pdf
C# I need assitance on my code.. Im getting an error message Us.pdfC# I need assitance on my code.. Im getting an error message Us.pdf
C# I need assitance on my code.. Im getting an error message Us.pdf
eyezoneamritsar
 
Need help with questions 2-4. Write assembly code to find absolute v.pdf
Need help with questions 2-4. Write assembly code to find absolute v.pdfNeed help with questions 2-4. Write assembly code to find absolute v.pdf
Need help with questions 2-4. Write assembly code to find absolute v.pdf
feelinggifts
 
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
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
TashiBhutia12
 

Ähnlich wie Lec 7 28_aug [compatibility mode] (20)

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
 
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
 
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
 
Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision Detection
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2ME
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdfimport java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
 
C# I need assitance on my code.. Im getting an error message Us.pdf
C# I need assitance on my code.. Im getting an error message Us.pdfC# I need assitance on my code.. Im getting an error message Us.pdf
C# I need assitance on my code.. Im getting an error message Us.pdf
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
JDK and AWT
JDK and AWTJDK and AWT
JDK and AWT
 
Need help with questions 2-4. Write assembly code to find absolute v.pdf
Need help with questions 2-4. Write assembly code to find absolute v.pdfNeed help with questions 2-4. Write assembly code to find absolute v.pdf
Need help with questions 2-4. Write assembly code to find absolute v.pdf
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
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
 
Jfreechart tutorial
Jfreechart tutorialJfreechart tutorial
Jfreechart tutorial
 
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
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Mehr von Palak Sanghani

Mehr von 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
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+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@
 

Kürzlich hochgeladen (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+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...
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

Lec 7 28_aug [compatibility mode]

  • 1. Java Data types and Variables Lecture 7 Naveen Kumar
  • 2. Strings  A string is a sequence of characters  Strings are objects of the String class  String constants: "Hello, World!"  String variables: String message = "Hello, World!";  String length: int n = message.length();  Empty string: "" 2
  • 3. Concatenation  Use the + operator: String name = "Dave"; String message = "Hello, " + name; // message is "Hello, Dave"  If one of the arguments of the + operator is a string, the other is converted to a string String a = "Agent"; int n = 7; String bond = a + n; // bond is Agent7 3
  • 4. Converting between Strings and Numbers  Convert to number: int n = Integer.parseInt(str); double x = Double.parseDouble(x); int num = Integer.parseInt("1234");  Convert to string: String str = "" + n; str = Integer.toString(n); String str = String.valueOf(num);4
  • 5. Substrings  String greeting = "Hello, World!"; String sub = greeting.substring(0, 5); // sub is "Hello"  Supply start and end positions, end is not included  First position is at 0 5
  • 6. Self Check  Assuming the String variable s holds the value "Agent", what is the effect of the assignment s = s + s.length() ?  Assuming the String variable river holds the value "Mississippi", what is the value of river.substring(1, 2)? and river.substring(2, river.length() - 3)? Answers  s is set to the string Agent5  The strings "i" and  "ssissi" 6
  • 7. 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.*; 7
  • 8. 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); } } 8
  • 9. 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 9
  • 10. 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; . . . } } 10
  • 11. 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 package11
  • 12. 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 12
  • 13. An example (produce a drawing with two boxes) import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JPanel; 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 } } 13
  • 14. 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); } }14
  • 15. 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 15
  • 16. 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 16
  • 17. 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); } } 17
  • 18. 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); 18
  • 19. 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); 19
  • 20. 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); 20 Upper-left corner, Width , Height
  • 21. 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 21
  • 22. 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; 22
  • 23. 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); 23
  • 24. 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); 24
  • 25. 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); ColoredSquarecomponent = new ColoredSquare (fillColor); frame.add(component); frame.setVisible(true); } }25
  • 26. Example cont. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; public class ColoredSquare extends Jcomponent { private Color fillColor; public ColoredSquare (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 final int SQUARE_LENGTH = 100; Rectangle square = new Rectangle((getWidth() - SQUARE_LENGTH) / 2, (getHeight() SQUARE_LENGTH) / 2, SQUARE_LENGTH, SQUARE_LENGTH); g2.fill(square); } }26