32
Graphical User Interface Bonus slides Interaction Between Components & Drawing

Graphical User Interface Bonus slides Interaction Between Components & Drawing

Embed Size (px)

Citation preview

Page 1: Graphical User Interface Bonus slides Interaction Between Components & Drawing

Graphical User Interface

Bonus slides

Interaction Between Components & Drawing

Page 2: Graphical User Interface Bonus slides Interaction Between Components & Drawing

2

• Write a Java program that creates a window titles Silly String Name that is 300 by 100 pixels.

• The user can type text into the text field.

• When the user presses a button labeled “Upper case”, the text is capitalized.

• When the user presses a button labeled “Lower Case”, the text is made lower case

Interaction Between Components

Page 3: Graphical User Interface Bonus slides Interaction Between Components & Drawing

3

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class SillyStringGUI { public static void main(String[] args) { SillyStringGUI gui = new SillyStringGUI(); } private JFrame frame; private JTextField textField; private JButton uppercase; private JButton lowercase;

Interaction Between Components

Page 4: Graphical User Interface Bonus slides Interaction Between Components & Drawing

4

public SillyStringGUI() { textField = new JTextField("The text can be made to all

upper case or lower case"); uppercase = new JButton("Upper Case"); lowercase = new JButton("Lower Case"); uppercase.addActionListener(new UpperCaseListener()); lowercase.addActionListener(new LowerCaseListener()); JPanel north = new JPanel(new FlowLayout()); north.add(uppercase); JPanel south = new JPanel(new FlowLayout()); south.add(lowercase); frame = new JFrame(); frame.setTitle("Silly String Game"); frame.setSize(300, 150); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.add(north, BorderLayout.NORTH); frame.add(textField, BorderLayout.CENTER); frame.add(south, BorderLayout.SOUTH); frame.setVisible(true); }

Interaction Between Components

Page 5: Graphical User Interface Bonus slides Interaction Between Components & Drawing

5

public class UpperCaseListener implements ActionListener { public void actionPerformed(ActionEvent event) { textField.setText(textField.getText().toUpperCase()); } } public class LowerCaseListener implements ActionListener { public void actionPerformed(ActionEvent event) { textField.setText(textField.getText().toLowerCase()); } }}

Interaction Between Components

• LowerCaseListener and UpperCaseListener are Inner classes .

Page 6: Graphical User Interface Bonus slides Interaction Between Components & Drawing

6

Inner Classes (15.4 p 945)• Inner classes are convenient for insignificant classes. • Trivial classes can be defined inside a method

• If inner class is defined inside an enclosing class, but outside its methods, it is available to all methods of enclosing class

• Compiler turns an inner class into a regular class file

• Methods of inner classes can access variables and fields from the surrounding scope.Declared inside a method class OuterClassName { method signature { . . . class InnerClassName { // methods // fields } . . . } . . . }

Declared inside the class class OuterClassName { // methods // fields accessSpecifier class InnerClassName

{ // methods // fields } . . . }

Page 7: Graphical User Interface Bonus slides Interaction Between Components & Drawing

7

JScrollPane• A special container that holds a component, using scrollbars to allow

that component to be seen. It wraps the given component with scrollbars.

public JScrollPane(Component comp)

• To add scroll bars to a text area: JTextArea textArea = new JTextArea(ROWS, COLUMNS);JScrollPane scrollPane = new JScrollPane(textArea);

• After constructing the scroll pane, add the scroll pane to the container, not the original component.frame.add(scrollPane);

frame.add(scrollPane, BorderLayout.CENTER);

Page 8: Graphical User Interface Bonus slides Interaction Between Components & Drawing

8

JFileChooser

• public int showOpenDialog(Component parent)– Pops up an "Open File" file chooser dialog.

• public int showSaveDialog(Component parent)– Pops up a "Save File" file chooser dialog.

• public File getSelectedFile()– Returns the selected file.

• public static int APPROVE_OPTION, CANCEL_OPTION– Possible result values from showXxxDialog(..).

• Special dialog box that allows the user to select file(s)/folder(s)

• public JFileChooser()–  Constructs a JFileChooser pointing to the

user's default directory.

• public JFileChooser(String currentDir)– Constructs a JFileChooser using the given

path

Page 9: Graphical User Interface Bonus slides Interaction Between Components & Drawing

9

JFileChooser-Example

JFileChooser fileChooser = new JFileChooser();

int result = fileChooser.showSaveDialog(frame);

if (result == JFileChooser.APPROVE_OPTION)

String filename = fileChooser.getSelectedFile().toString();

//fileChooser.getSelectedFile().getName() should work also

Page 10: Graphical User Interface Bonus slides Interaction Between Components & Drawing

2D Graphics

Page 11: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• In Java drawings are displayed inside a frame window.

• We have seen how to create a frame window.

• we will learn how to create a drawing inside the frame.

Graphical Applications and Frame Windows

11

Page 12: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• You cannot draw directly onto a frame.−To display a drawing in a frame, you have to construct a component object and

add it to the frame.

• To define a component object, define a class that extends the JComponent class.

• Place drawing instructions inside the paintComponent method. That method is called whenever the component needs to be repainted.

public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Drawing instructions go here } }

Drawing on a Component

12

Page 13: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• 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:

public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } }

Continued

Classes Graphics and Graphics2D

13

Page 14: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• Call method draw of the Graphics2D class to draw shapes, such as rectangles, ellipses, line segments, polygons, and arcs:

public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { . . . Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); . . . } }

Classes Graphics and Graphics2D (cont.)

14

Page 15: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import java.awt.Graphics;02: import java.awt.Graphics2D;03: import java.awt.Rectangle;04: import javax.swing.JComponent;05: 07: // A component that draws two rectangles.09: public class RectangleComponent extends JComponent10: { 11: public void paintComponent(Graphics g)12: { 13: // Recover Graphics2D14: Graphics2D g2 = (Graphics2D) g;15: 16: // Construct a rectangle and draw it17: Rectangle box = new Rectangle(5, 10, 20, 30);18: g2.draw(box);19: 20: // Move rectangle 15 units to the right and 25 units down21: box.translate(15, 25);22: 23: // Draw moved rectangle24: g2.draw(box);25: }26: }

RectangleComponent.java

15

Page 16: Graphical User Interface Bonus slides Interaction Between Components & Drawing

1. Construct a frame.

2. Construct an object of your component class: RectangleComponent component = new RectangleComponent();

3. Add the component to the frame: frame.add(component);

4. Make the frame visible

Using a Component

16

Page 17: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import javax.swing.JFrame;02: 03: public class RectangleViewer04: {05: public static void main(String[] args)06: {07: JFrame frame = new JFrame();08: 09: frame.setSize(300, 400);10: frame.setTitle("Two rectangles");11: frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);12: 13: RectangleComponent component =

new RectangleComponent();14: frame.add(component);15: 16: frame.setVisible(true);17: }18: }

RectangleViewer.java

17

Page 18: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• Ellipse2D.Double describes an ellipse

• This class is an inner class – 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);

Ellipses

18

Page 19: Graphical User Interface Bonus slides Interaction Between Components & Drawing

Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); g2.draw(segment);

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); g2.draw(segment);

Drawing Lines

19

Page 20: Graphical User Interface Bonus slides Interaction Between Components & Drawing

                                                                                                                                                                           

g2.drawString(“Message”, 50, 100);

• 50 and 100 are the x- and y- coordinates of the base point of the first character in the string

Drawing Text   

20

Page 21: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• Standard colors Color.BLUE, Color.RED, Color.PINK etc.

• Specify red, green, blue between 0 and 255 Color magenta = new Color(255, 0, 255);

− Constructs a color object with maximum red, no green, and maximum blue

• Set color in graphics contextg2.setColor(magenta);

• Color is used when drawing and filling shapesg2.fill(rectangle); // filled with current color

Colors

21

Page 22: Graphical User Interface Bonus slides Interaction Between Components & Drawing

Alien Face

22

Page 23: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import java.awt.Color;02: import java.awt.Graphics;03: import java.awt.Graphics2D;04: import java.awt.Rectangle;05: import java.awt.geom.Ellipse2D;06: import java.awt.geom.Line2D;07: import javax.swing.JPanel;08: import javax.swing.JComponent;09: 10: /**11: A component that draws an alien face12: */13: public class FaceComponent extends JComponent14: { 15: public void paintComponent(Graphics g)16: { 17: // Recover Graphics2D 18: Graphics2D g2 = (Graphics2D) g;19:

Continued

FaceComponent.java

23

Page 24: Graphical User Interface Bonus slides Interaction Between Components & Drawing

20: // Draw the head21: Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);22: g2.draw(head);23: 24: // Draw the eyes25: Line2D.Double eye1 = new Line2D.Double(25, 70, 45, 90);26: g2.draw(eye1);27: 28: Line2D.Double eye2 = new Line2D.Double(85, 70, 65, 90);29: g2.draw(eye2);30: 31: // Draw the mouth32: Rectangle mouth = new Rectangle(30, 130, 50, 5);33: g2.setColor(Color.RED);34: g2.fill(mouth);35: 36: // Draw the greeting37: g2.setColor(Color.BLUE);38: g2.drawString("Hello, World!", 5, 175);39: }40: }

FaceComponent.java (cont.)

24

Page 25: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import javax.swing.JFrame;02: 03: public class FaceViewer04: {05: public static void main(String[] args)06: {07: JFrame frame = new JFrame();08: frame.setSize(300, 400);09: frame.setTitle("An Alien Face");10: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);11: 12: FaceComponent component = new FaceComponent();13: frame.add(component);14: 15: frame.setVisible(true);16: }17: }

FaceViewer.java

25

Page 26: Graphical User Interface Bonus slides Interaction Between Components & Drawing

Drawing Cars

26

• The coordinates of the car parts seem a bit arbitrary. To come up with suitable values:

• Draw the image on graph paper and read off the coordinates.

Page 27: Graphical User Interface Bonus slides Interaction Between Components & Drawing

• The paintComponent method of the CarComponent class should draw two cars: one in top-left corner, and another in the bottom-right corner

• To compute bottom-right position, inside paintComponent method, we call the getWidth and getHeight methods of Jcomponent class:

− These methods return the dimensions of the component. Then , we subtract the dimension of the car.

Car car1 = new Car(0, 0); int x = getWidth() - 60; int y = getHeight() - 30;

Car car2 = new Car(x, y);

• getWidth and getHeight have no implicit parameter. They are applied to the object that executes paintComponent

− The component simply obtains its own width and height • The second car always ends up at the bottom right corner. If window

is resized paintComponent is called and car position recomputed

Drawing Cars (This example is for you to read/apply)

27

Page 28: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import java.awt.Graphics2D;02: import java.awt.Rectangle;03: import java.awt.geom.Ellipse2D;04: import java.awt.geom.Line2D;05: import java.awt.geom.Point2D;06: 07: /**08: A car shape that can be positioned anywhere on the screen.09: */10: public class Car11: {12: /**13: Constructs a car with a given top left corner14: @param x the x coordinate of the top left corner15: @param y the y coordinate of the top left corner16: */17: public Car(int x, int y)18: {19: xLeft = x;20: yTop = y;21: }22:

Continued

Car.java

28

Page 29: Graphical User Interface Bonus slides Interaction Between Components & Drawing

23: /**24: Draws the car.25: @param g2 the graphics context26: */27: public void draw(Graphics2D g2)28: {29: Rectangle body 30: = new Rectangle(xLeft, yTop + 10, 60, 10); 31: Ellipse2D.Double frontTire 32: = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10);33: Ellipse2D.Double rearTire34: = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10);35: 36: // The bottom of the front windshield37: Point2D.Double r1 38: = new Point2D.Double(xLeft + 10, yTop + 10);39: // The front of the roof40: Point2D.Double r2 41: = new Point2D.Double(xLeft + 20, yTop);42: // The rear of the roof43: Point2D.Double r3 44: = new Point2D.Double(xLeft + 40, yTop);45: // The bottom of the rear windshield

Continued

Car.java (cont.)

29

Page 30: Graphical User Interface Bonus slides Interaction Between Components & Drawing

46: Point2D.Double r4 47: = new Point2D.Double(xLeft + 50, yTop + 10);48: 49: Line2D.Double frontWindshield 50: = new Line2D.Double(r1, r2);51: Line2D.Double roofTop 52: = new Line2D.Double(r2, r3);53: Line2D.Double rearWindshield54: = new Line2D.Double(r3, r4);55: 56: g2.draw(body);57: g2.draw(frontTire);58: g2.draw(rearTire);59: g2.draw(frontWindshield); 60: g2.draw(roofTop); 61: g2.draw(rearWindshield); 62: } //end of draw method63: 64: private int xLeft;65: private int yTop;66: } //end of class Car

Car.java (cont.)

30

Page 31: Graphical User Interface Bonus slides Interaction Between Components & Drawing

import java.awt.Graphics;import java.awt.Graphics2D;import javax.swing.JComponent; //This component draws two car shapes.public class CarComponent extends JComponent{ public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g;

Car car1 = new Car(0, 0); int x = getWidth() - 60; int y = getHeight() - 30; Car car2 = new Car(x, y); car1.draw(g2); car2.draw(g2); }}

CarComponent.java

31

Page 32: Graphical User Interface Bonus slides Interaction Between Components & Drawing

01: import javax.swing.JFrame;02: 03: public class CarViewer04: {05: public static void main(String[] args)06: {07: JFrame frame = new JFrame();08: 09: frame.setSize(300, 400);10: frame.setTitle("Two cars");11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);12: 13: CarComponent component = new CarComponent();14: frame.add(component);15: 16: frame.setVisible(true);17: }18: }19:

CarViewer.java

32