320 likes | 470 Views
Graphical User Interface. Bonus slides Interaction Between Components & Drawing. Interaction Between Components. 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.
E N D
Graphical User Interface Bonus slides Interaction Between Components & Drawing
Interaction Between Components • 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 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 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 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()); } } } • LowerCaseListener and UpperCaseListener are Innerclasses .
Inner Classes (15.4 p 945) • Innerclasses are convenient for insignificant classes. • Trivialclasses 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 innerclasses 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 // fieldsaccessSpecifier class InnerClassName {// methods // fields } . . . }
JScrollPane • A special container that holds a component, using scrollbars to allow that component to be seen. It wrapsthe given component with scrollbars. public JScrollPane(Component comp) • To add scroll bars to a text area: JTextAreatextArea = new JTextArea(ROWS, COLUMNS);JScrollPanescrollPane = 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);
JFileChooser • Special dialog box that allows the user to select file(s)/folder(s) • 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(..). • public JFileChooser() • Constructs a JFileChooser pointing to the user's default directory. • public JFileChooser(String currentDir) • Constructs a JFileChooserusing the given path
JFileChooser-Example JFileChooserfileChooser = new JFileChooser(); int result = fileChooser.showSaveDialog(frame); if (result == JFileChooser.APPROVE_OPTION) String filename = fileChooser.getSelectedFile().toString(); //fileChooser.getSelectedFile().getName() should work also
Graphical Applications and Frame Windows • 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. 11
Drawing on a Component • 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 JComponentclass. • Place drawing instructions insidethe paintComponentmethod. 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 } } 12
Classes Graphics and Graphics2D • Graphicsclass lets you manipulate the graphics state (such as current color) • Graphics2Dclass has methods to draw shape objects • Use a cast to recover the Graphics2Dobject from the Graphics parameter: public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } } Continued 13
Classes Graphics and Graphics2D(cont.) • Call method draw of the Graphics2Dclass 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); . . . } } 14
RectangleComponent.java 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:publicclass RectangleComponent extends JComponent 10:{ 11:publicvoidpaintComponent(Graphics g) 12:{ 13:// Recover Graphics2D 14:Graphics2D g2 = (Graphics2D) g; 15: 16:// Construct a rectangle and draw it 17: Rectangle box =newRectangle(5,10,20,30); 18: g2.draw(box); 19: 20:// Move rectangle 15 units to the right and 25 units down 21: box.translate(15,25); 22: 23:// Draw moved rectangle 24: g2.draw(box); 25:} 26:} 15
Using a Component • Construct a frame. • Construct an object of your component class: RectangleComponent component = new RectangleComponent(); • Add the component to the frame:frame.add(component); • Make the frame visible 16
RectangleViewer.java 01:import javax.swing.JFrame; 02: 03:publicclass RectangleViewer 04:{ 05:publicstaticvoidmain(String[] args) 06:{ 07: JFrame frame =newJFrame(); 08: 09: frame.setSize(300,400); 10: frame.setTitle("Two rectangles"); 11: frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); 12: 13: RectangleComponent component = newRectangleComponent(); 14: frame.add(component); 15: 16: frame.setVisible(true); 17:} 18:} 17
Ellipses • Ellipse2D.Doubledescribes 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 drawthe shape • Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, • height); • g2.draw(ellipse); 18
Drawing Lines 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); 19
Drawing Text 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 20
Colors • Standard colors Color.BLUE, Color.RED, Color.PINK etc. • Specify red, green, blue between 0and255 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 21
Alien Face 22
FaceComponent.java 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 face 12:*/ 13:publicclass FaceComponent extends JComponent 14:{ 15:publicvoidpaintComponent(Graphics g) 16:{ 17:// Recover Graphics2D 18: Graphics2D g2 =(Graphics2D) g; 19: Continued 23
FaceComponent.java (cont.) 20:// Draw the head 21: Ellipse2D.Double head =new Ellipse2D.Double(5,10,100,150); 22: g2.draw(head); 23: 24:// Draw the eyes 25: 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 mouth 32: Rectangle mouth =newRectangle(30,130,50,5); 33: g2.setColor(Color.RED); 34: g2.fill(mouth); 35: 36:// Draw the greeting 37: g2.setColor(Color.BLUE); 38: g2.drawString("Hello, World!",5,175); 39:} 40:} 24
FaceViewer.java 01:import javax.swing.JFrame; 02: 03:publicclass FaceViewer 04:{ 05:publicstaticvoidmain(String[] args) 06:{ 07: JFrame frame =newJFrame(); 08: frame.setSize(300,400); 09: frame.setTitle("An Alien Face"); 10: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11: 12: FaceComponent component =newFaceComponent(); 13: frame.add(component); 14: 15: frame.setVisible(true); 16:} 17:} 25
Drawing Cars • 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. 26
Drawing Cars (This example is for you to read/apply) • The paintComponentmethod of the CarComponentclass 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 andgetHeight methods of Jcomponentclass: • 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 resizedpaintComponent is called and car position recomputed 27
Car.java 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:publicclass Car 11:{ 12:/** 13: Constructs a car with a given top left corner 14:@param x the x coordinate of the top left corner 15:@param y the y coordinate of the top left corner 16: */ 17:publicCar(int x,int y) 18:{ 19: xLeft = x; 20: yTop = y; 21:} 22: Continued 28
Car.java (cont.) 23:/** 24: Draws the car. 25:@param g2 the graphics context 26: */ 27:publicvoiddraw(Graphics2D g2) 28:{ 29: Rectangle body 30:=newRectangle(xLeft, yTop +10,60,10); 31: Ellipse2D.Double frontTire 32:=new Ellipse2D.Double(xLeft +10, yTop +20,10,10); 33: Ellipse2D.Double rearTire 34:=new Ellipse2D.Double(xLeft +40, yTop +20,10,10); 35: 36:// The bottom of the front windshield 37: Point2D.Double r1 38:=new Point2D.Double(xLeft +10, yTop +10); 39:// The front of the roof 40: Point2D.Double r2 41:=new Point2D.Double(xLeft +20, yTop); 42:// The rear of the roof 43: Point2D.Double r3 44:=new Point2D.Double(xLeft +40, yTop); 45:// The bottom of the rear windshield Continued 29
Car.java (cont.) 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 rearWindshield 54:=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 method 63: 64:privateint xLeft; 65:privateint yTop; 66:} //end of class Car 30
CarComponent.java import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; //This component draws two car shapes. publicclass CarComponent extends JComponent { publicvoidpaintComponent(Graphics g) { Graphics2D g2 =(Graphics2D) g; Car car1 =newCar(0,0); int x =getWidth()-60; int y =getHeight()-30; Car car2 =newCar(x, y); car1.draw(g2); car2.draw(g2); } } 31
CarViewer.java 01:import javax.swing.JFrame; 02: 03:publicclass CarViewer 04:{ 05:publicstaticvoidmain(String[] args) 06:{ 07: JFrame frame =newJFrame(); 08: 09: frame.setSize(300,400); 10: frame.setTitle("Two cars"); 11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12: 13: CarComponent component =newCarComponent(); 14: frame.add(component); 15: 16: frame.setVisible(true); 17:} 18:} 19: 32