0% found this document useful (0 votes)
3 views

L1_Graphics_programming___Inner_classes

The document provides an overview of graphics programming in Java, focusing on creating and manipulating frames using the Swing library. It explains how to create a closable frame, add components like text and shapes, and handle events for closing the application. Additionally, it covers the use of inner classes in Java for event-driven programming, demonstrating their convenience in GUI applications.

Uploaded by

KARZAN -t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

L1_Graphics_programming___Inner_classes

The document provides an overview of graphics programming in Java, focusing on creating and manipulating frames using the Swing library. It explains how to create a closable frame, add components like text and shapes, and handle events for closing the application. Additionally, it covers the use of inner classes in Java for event-driven programming, demonstrating their convenience in GUI applications.

Uploaded by

KARZAN -t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Graphics Programming

Java has extensive support for graphics programming. In the next few lectures
we will write Java applications which manipulate windows or frames, text, fonts,
colours, shapes etc.

We will start with creating a closable frame, i.e. atop-level window that is not
inside another window:
import javax.swing.*;
class myFrame1 extends JFrame{
public myFrame1(){
setTitle(“My First Frame");
setSize(300,200);
}
public static void main(String[] a){
JFrame frame=new myFrame1();
frame.show();
}
}

Object Oriented Programming in Java 1


Graphics Programming 2

Java includes a set of classes for dealing with graphics; these classes are
stored in a package called Swing. The first line of this program imports
this package.

We then create class myFrame1 which extends the Java JFrame class
which is a Swing class. We use the methods setTitle and setSize
from JFrame class to give the frame a title and specify the size. The output
of this simple program is the following window:

A blank frame which you can


resize, maximize, minimize, move,
and close. The frame also has a
system menu to perform the above
operations (click the top left-hand
corner Icon) Most of this behaviour is
Inherited from parent classes.

Object Oriented Programming in Java 2


Graphics Programming 3

A frame is a container object which can hold other user interface elements
such as buttons, menus, text fields, etc. To show a frame you need to
follow the three steps:

1- Create the frame object by a call to new


2- Optionally, position the frame on the user’s screen, using the
setLocation methods. By default, the frame will be placed in the top-
left corner.
3- Call the show method to make the frame visible and to bring it to the
front if it is behind another window.

There is one problem with this little program; you will find it hard to end the
program. To properly close this graphics program, add the following event
handler to the class:

Object Oriented Programming in Java 3


Graphics Programming 4
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
This is an event handler; which listens for the event of closing the frame.
Event handlers will be discussed later.

To change how your frames look like, you can use inherited methods from
the JFrame and its parent classes. The most common layout methods are
the following:
- setIconImage method to set an icon for your frames
- setTitle method to set some text in the title bar
- setResizable method determine if a frame will be resizable by the user
- setLocation method to set the position for your frame

Object Oriented Programming in Java 4


Graphics Programming 5

This next example will create a frame with an area one-forth that of the
whole screen and is positioned in the middle of the screen. For this
example, we need to obtain the screen resolution:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class myFrame2 extends JFrame{
public myFrame2(){
setTitle("Centered Frame");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Object Oriented Programming in Java 5


Graphics Programming 6
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension d=tk.getScreenSize();
int sHeight=d.height; //get screen height
int sWidth=d.width; //get screen width

setSize(sWidth/2,sHeight/2);
setLocation(sWidth/4,sHeight/4);
Image img=tk.getImage("icon.gif");//window icon
setIconImage(img);
}
public static void main(String[] a){
JFrame frame=new myFrame2();
frame.setVisible(true);
}
}
Java uses the Toolkit class to access system-dependent information.

Object Oriented Programming in Java 6


Graphics Programming 7
The Toolkit class has a method called getScreenSize() which returns
the screen size as a dimension object. A Dimension object stores both the
height and width of the screen.

We also need to interact with the operating system to obtain an image stored in
the file-system using the Toolkit class method getImage:
Image img=tk.getImage(“icon.gif”);
You could specify long paths, e.g. “D:/Pictures/icon.gif”

The output from this program is the following frame:


Of course, the frame here has been resized to
fit this slide. It will be placed in the middle of
Your screen and its area will be one-forth that
of the screen size. Also note the user-specified
Icon in the title bar and the inactive maximize
Icon.

Object Oriented Programming in Java 7


Graphics Programming 8
Now will see how we can add text to our frames. Remember, a frame is a
container object which you can add other elements to it. To add some text to a
frame for example:
1- create a class that extends the JPanel class (this can be used to draw
graphics and text)
2- Override the paintComponent method in that class
3- add an object of this class to the content pane of the frame:

The following example demonstrates these steps:


class HelloWorldPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(“Hello World”, 75, 100);
}
class HelloWorldFrame extends JFrame {
public HelloWorldFrame(){

Object Oriented Programming in Java 8


Graphics Programming 9
setTitle(“Hello World”); setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Container contentPane=getContentPane();//get content pane
contentPane.add(new HelloWorldPanel()); //on the fly
} //add panel component to the content pane
}
public class HelloWorld{
public static void main(String[] args){
JFrame frame=new HelloWorldFrame();
frame.setVisible(true);
}
}

Object Oriented Programming in Java 9


Graphics Programming 10
To display text, you must first select a font. To select a font, you must first
create an object of class Font. The following example will create three fonts
and display text using each font in turn:
class HelloWorldPanel2 extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
f=new Font("SansSerif", Font.BOLD, 14);
f1=new Font("Trebusbi", Font.PLAIN, 24);
f2=new Font("Verdana",Font.BOLD+Font.ITALIC, 22);
g.setFont(f);
g.drawString("Hello World", 75, 50);
g.setFont(f1);
g.drawString("Hello World", 75, 75);
g.setFont(f2);
g.drawString("Hello World", 75, 100);
}

Object Oriented Programming in Java 10


Graphics Programming 11
private Font f, f1,f2;
}
For brevity, the rest of the program has been omitted. This was the panel class
definition. You can just add this panel to the frame from the last example and it
should work.

In this example, we declare three font objects f, f1 and f2. Before drawing the
string, the fonts are applied to the graphics object. You can use any font
available on your machine. But you should be aware that not all machines
have the same fonts installed.

A Font object takes 3 parameters: the


First is the font-family, the second is the
Font style and the third is the font point size.
Font style are: PLAIN, BOLD, ITALIC and
Combinations of BOLD and ITALIC

Object Oriented Programming in Java 11


Graphics Programming 12
The setColor method of the java.awt.Graphics class lets you select a
color that is used for the subsequent drawing operations on the graphics
context or component. To draw in multiple colors, select a color, draw, then
select another color and draw again.

Java supports 13 standard colors: black, blue, cyan, darkGray,


gray, green, lightGreen, magenta, orange, pink, red,
white, yellow.

Or you can create a Color object and then specify its color by specifying its
red, green and blue components: Color(byte redness, byte
greenness, byte blueness)

To set the color for the graphics object:


g.setColor(Color.red); or
g.setColor(new Color(0, 100,122);

Object Oriented Programming in Java 12


Graphics Programming 13
You can use the drawLine, drawArc, drawPolyLine and drawPolygon methods
in java.awt.Graphics to draw straight and curved lines on a graphics object.
This example draws a number of shapes:

class ShapesPanel extends JPanel {


public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
//draw a triangle
g.drawLine(20,20,20,100);
g.drawLine(20,100, 120,20);
g.drawLine(120,20,20,20);
//draw a circle
g.drawArc(220,20, 100, 100, 0,360);
}

Object Oriented Programming in Java 13


Graphics Programming 14
//draw a 5-sided polugon
Polygon p=new Polygon();
p.addPoint(60,150);
p.addPoint(70,170);
p.addPoint(150,160);
p.addPoint(140,70);
p.addPoint(70,115);
g.drawPolygon(p);
}
}
This would output:

Using a combination of lines,


Arcs and polygons, you can draw
Any shape you like.

Object Oriented Programming in Java 14


Graphics Programming 15
Add this panel object to the your frame. This example used a number of
drawing methods. For straight lines:

drawLine( int x1, int y1, int x2, int y2);


draw line from (x1,y1) to (x2, y2)

To draw an arc:
drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle);

This will draw an arc bounded by rectangle [x,y,width, height] and with start
angle and span angle. For a circle the start angle would be 0 and the span
angle would be 360.

You can also use drawRect, drawRoundRect draw3DRect and drawOval to


draw rectangles and ellipses. See the example on the next slide.

Object Oriented Programming in Java 15


Graphics Programming 16
This example draws some more shapes:
class ShapesPanel extends JPanel {
public void paintComponent(Graphics g)
{ super.paintComponent(g);
g.drawRect(10,10,80,40);
g.drawRoundRect(100,10, 100,50, 30,30);
g.drawOval(10,100, 80,30);
g.drawOval(100,100, 80,80);//cirlce
g.draw3DRect(200,100,80,40,true);
int thinkness=4;
for(int i=0; i<thinkness; i++)
g.draw3DRect(230-i, 10-i, 80+2 * i,
40+2*i,true);
g.setColor(Color.blue);
g.fillRoundRect(300,100, 80,40,20,20);
}
}
Object Oriented Programming in Java 16
Graphics Programming 17
The output from this panel would be:

Note the draw3Drect; this method


Draws a 3-d rectangle but since the
Border is only 1 pixel thick, you
Cannot see a 3-d rectangle. Hence
The for-loop to draw several
Rectangles.

The last method draws and fills a round rectangle at the same time. You can
also use fillRect, fill3DRect, fillOval ,fillPolygon,
fillArc to draw other filled shapes.

Object Oriented Programming in Java 17


OO programming (inner classes)

An inner class is a class that is defined inside another class. One of the
main reasons of having inner classes is because they are very convenient
when you are writing event-driven programs in Java. Since we will study
GUI and event-driven programming later on, we need to understand inner
classes in detail.

Inner classes are defined inside other classes. The following example
demonstrates this feature:
Public class Parcel{
class Contents{
private int i=1;
public int value(){return i;}
}
class Destination{
private String label;
Destination(String whereTo){ label=whereTo;}
String readLabel() {return label;}

Object Oriented Programming in Java 18


OO programming (inner classes)

}
public void ship(String dest){
Contents c=new Contents();
Destination d=new Destination(dest);
System.out.println(d.readLabel());
}
public static void main(String[] a){
Parcel p=new Parcel();
p.ship(“London”);
}
}
This example shows how you can create and use inner classes. In this
example, two inner classes are defined inside the outer class Parcel. In
the method ship(), objects are created of type Contents and Destination.
When you compile this program, 3 class files are created, one for each
class. Inner classes are given the name of OuterClass$InnerClass format.

Object Oriented Programming in Java 19

You might also like