Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Swing: Creating Graphics Interfaces with JFrame and JPanel - Prof. Travis Doom, Study notes of Computer Science

An introduction to creating graphics interfaces using java swing. It covers the basics of using jframe and jpanel components, as well as creating custom components by extending jpanel and overriding the paintcomponent() method. The document also touches upon the use of graphics and graphics2d classes for drawing shapes and animating components.

Typology: Study notes

Pre 2010

Uploaded on 08/16/2009

koofers-user-yg0
koofers-user-yg0 🇺🇸

5

(1)

10 documents

1 / 10

Toggle sidebar

Related documents


Partial preview of the text

Download Java Swing: Creating Graphics Interfaces with JFrame and JPanel - Prof. Travis Doom and more Study notes Computer Science in PDF only on Docsity!

Introductory Graphics in JavaIntroductory Graphics in Java

Swing

Jframe objects

Jpanel components

Easy GUI Interfaces:Easy GUI Interfaces: JOptionPane

JOptionPane

import javax.swing.*;public static void main (String[] args) {public static void main (String[] args) {

JOptionPane.showMessageDialog (null, "Hello World!"); } // end method main import javax.swing.*; public static void main (String[] args) {

String filename = JOptionPane.showInputDialog (null,

"Enter filename:");

System.out.println(filename); } //

d^

h^

d^

i

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^

// end method main

Swing library:Swing library: JFrame

JFrame

Ti l B

JF

Ti

tleBar

JFrame

JP

l C

P

MenuBar

JPanel ContentPane

JComponent

JComponent

Position determined by:

JComponent

Position determined by:- order in list- layout type

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Creating a windowCreating a window

z^

The JFrame class represents an object that you can display on the screen.

A JFrame holds a title bar menu bar and content pane

–^

A JFrame holds a title bar, menu bar, and content pane.

–^

Essentially JFrame is your “standard”/abstract window object.

z^

You can “nest” components in each other. Syntax is like ArrayList.–

Swing library classes exist for: buttons, menus, radio buttons, labels,text entry areas, check boxes, and other standard GUI widgets.

z^

After adding components, call methods to layout/display the window.

import javax.swing.*;… JFrame frame = new JFrame();

// Step 1: Make a window frame

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel contentPane = (JPanel) frame.getContentPane();JLabel label = new JLabel("Hello World!"); // Step 2: Make componentscontentPane.add(label);

// Step 3: Nest components

frame.setSize(300,300);

// Step 4: Display frame

frame.setVisible(true);

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

(^

);

Making your own component: extendMaking your own component: extend JPanel

JPanel

z^

To put your own images on the screen, you need to make a 2D graphicscomponent (a paintable widget).

z^

The easiest way to do this is to extend the JPanel class and override itsbehavior with the specific behavior of your component

z^

You only need to override paintComponent()!

y^

p^

p^

()

z^

The JFrame calls the paintComponent() method of each of its components whenever itfeels the display needs to be refreshed. It’s a contract. If you want to be a component,then you must have a paintComponent().

z^

Y^

ill

ll^

i tC

t^

lf ( lth

h^

k f

i t())

z^

You will never call paintComponent yourself (although you can ask for a repaint()).

import java.awt.*;

// Old library classes, you still need them

import javax.swing.*;

// New library classes, Swing extends AWT

class MyComponent extends Jpanel {

public void paintComponent (Graphics g) {

// your code to tell “g” how to “paint” your object goes here } // end method paintComponent

} //

d^

l^

M C

t

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^

// end class

MyComponent

Painting a component with a graphics objectPainting a component with a graphics object^ public void paintComponent (Graphics g) {

g.setColor(Color.red);

// Dip the paintbrush in red//

g.fillRect(20,50,100,100);

// Paint a

100x100 rectangle @ (20,50)

} // end method paintComponentpublic void paintComponent (Graphics g) {

Image image

new ImageIcon("rose

jpg") getImage();

Image image = new ImageIcon("rose.jpg").getImage();g.drawImage(image,2,2,this); } // end method paintComponent

bli

id

i^

tC

t (G

hi

) {

public void paintComponent (Graphics g) {

g.setColor(Color.black);

// set color black

g.fillRect(0,0,this.getWidth(),this.getHeight()); // paint backgroundint red =

(int) (Math.random() * 255);

int green = (int) (Math.random() * 255);

g int blue =

(int) (Math.random() * 255);

Color randomColor = new Color (red, green, blue);g.setColor(randomColor);

// set RGB color randomly

g.fillOval(70,70,100,100);

// paint 100x100 oval @ (70,70)

} // end method paintComponent

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^

// end method paintComponent

Graphics classesGraphics classes

z^

The argument to paintComponent is type java.awt.Graphics

g IS A Graphics

–^

g IS-A Graphics

z^

In the swing library, g is

actually

an instance of the subclass

javax.swing.Graphics2D which

extends

java.awt.Graphics

Th

th

bj

t^

h^

t^

G

hi

2D

th d

b t

’ll

d t

z^

Th

us, the object g has access to Graphics2D methods, but you’ll need to

typecast to get access them!

Graphics

p

drawImage()drawLine()drawPolygon()drawRect()

Graphics2Drotate()scale()

()

drawOval()fillRect()setColor()…

()

transform()…

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Simple animation: Test ClassSimple animation: Test Class

import javax.swing.*;public class Main {

public static void pause () {

try {

Thread.sleep (5);

// wait 5ms

} catch (Exception e) {

e.printStackTrace (); }} } // end method pausepublic static void main (String[] args) {

JFrame frame = new JFrame();frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);frame.setSize (300,300);frame.setVisible (true);BouncingBallPanel ballPanel = new BouncingBallPanel();frame.getContentPane ().add (ballpanel);while (true) {while (true) {

pause();ballPanel.move();ballPanel.repaint(); } } //

d^

h d

i

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^

// end method main

} // end class Main

Simple animation: Bouncing BallSimple animation: Bouncing Ball

import javax.swing.;import java.awt.;public class BouncingBallPanel extends JPanel {

int x = 100; int y = 100; int ballSize = 20; int run = 1; int rise = 3;public void paintComponent (Graphics g) {

g.setColor(Color.black);g^

fillRect (

0

getWidth() getHeight());

g.fillRect (0,0,getWidth(),getHeight());g.setColor(Color.red);g.fillOval(x,y,ballSize,ballSize);

} // method paintComponent (required!)public void move () {

if (x < 0 || x > getWidth() -

ballSize) {

run = -run; } if (y < 0 || y > getHeight() - ballSize) {

rise =

-rise;

rise

rise;

} x += run;y += rise;

} // end method move } //

d^

l^

i^

ll

l

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^

// end class BouncingBallPanel

Example: Bouncing ballsExample: Bouncing balls

z^

How can we add multiple balls?

How can we allow differentiation? (color speed initial position etc)

–^

How can we allow differentiation? (color, speed, initial position, etc)

z^

How can we detect collisions and have the balls respond appropriately?

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II