CH10 - Graphical User Interfaces(2).pptx

CH10 - Graphical User Interfaces(2).pptx - Chapter 10 –...

This preview shows page 1 out of 52 pages.

Unformatted text preview: Chapter 10 – Graphical User Interfaces This presentation has been modified for ACO 102: Object-Oriented Programming. Chapter Goals To implement simple graphical user interfaces To add buttons, text fields, and other components to a frame window To handle events that are generated by buttons To write programs that display simple drawings 2 Frame Windows Java provides classes to create graphical applications that can run on any major graphical user interface A graphical application shows information inside a frame: a window with a title bar Java’s JFrame class allows you to display a frame It is part of the javax.swing package 3 The JFrame Class Five steps to displaying a frame: 1) Construct an object of the JFrame class JFrame frame frame == new new JFrame(); JFrame(); JFrame 2) Set the size of the frame frame.setSize(300,400); frame.setSize(300,400); 3) Set the title of the frame frame.setTitle(“An Empty Empty frame.setTitle(“An Frame”); Frame”); 4) Set the “default close operation” frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;; 5) Make it visible frame.setVisible (true); (true); frame.setVisible 4 EmptyFrameView.java Your JVM (Java Virtual Machine) does all of the work of displaying the frame on your GUI This application is portable to all supported GUIs! 5 Adding Components You cannot draw directly on a JFrame object Instead, construct an object and add it to the frame A few examples objects to add are: JComponent Jpanel JTextComponent JLabel public class class RectangleComponent RectangleComponent extends extends JComponent JComponent public {{ public void void paintComponent(Graphics paintComponent(Graphics g) g) public {{ // Drawing Drawing instructions instructions go go here here // }} }} Extend the JComponent Class and override its paintComponent method 6 Adding Panels If you have more than one component, put them into a panel (a container for other user-interface components), and then add the panel to the frame: First create the components JButton button button == new new JButton("Click JButton("Click me!"); me!"); JButton JLabel label = new JLabel("Hello, World!"); JLabel label = new JLabel("Hello, World!"); Then add them to the panel Use a JPanel to group multiple JPanel panel panel == new new JPanel(); JPanel(); JPanel user-interface components together. panel.add(button); panel.add(button); panel.add(label); panel.add(label); Add the panel to the frame frame.add(panel); frame.add(panel); 7 FilledFrameViewer.java 8 Using Inheritance to Customize Frames For complex frames: Design a subclass of JFrame Store the components as instance variables Initialize them in the constructor of your subclass public class class FilledFrame FilledFrame extends extends JFrame JFrame public {{ private JButton JButton button; button; private Components are instance variables private JLabel JLabel label; label; private private static static final final int int FRAME_WIDTH FRAME_WIDTH == 300; 300; private private static static final final int int FRAME_HEIGHT FRAME_HEIGHT == 100; 100; private }} Initialize and add them in the public FilledFrame() FilledFrame() public constructor of your subclass with a {{ helper method. createComponents(); createComponents(); setSize(FRAME_WIDTH, FRAME_HEIGHT); FRAME_HEIGHT); setSize(FRAME_WIDTH, }} 9 Using Inheritance to Customize Frames Create the button and label, and add them to a new panel Add the panel to the frame private void void createComponents() createComponents() private { { button == new new JButton("Click JButton("Click me!"); me!"); button label == new new JLabel("Hello, JLabel("Hello, World!"); World!"); label JPanel panel = new JPanel(); JPanel panel = new JPanel(); panel.add(button); panel.add(button); panel.add(label); panel.add(label); add(panel); add(panel); } } Then instantiate the customized frame from the main method public class class FilledFrameViewer2 FilledFrameViewer2 public {{ public static static void void main(String main(String args) args) public {{ JFrame frame frame == new new FilledFrame(); FilledFrame(); JFrame frame.setTitle("A frame with two two components"); components"); frame.setTitle("A frame with frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setVisible(true); } } }} 10 Events and Event Handling In a modern graphical user interface program, the user controls the program through the mouse and keyboard The user can enter information into text fields, pull down menus, click buttons, and drag scroll bars in any order The program must react to the user commands The program can choose to receive and handle events such as “mouse move” or a button push “action event” 11 Events and Action Listeners A program must indicate which events it wants to receive It does so by installing event listener objects An event listener object belongs to a class that you declare The methods of your event listener classes contain the instructions that you want to have executed when the events occur To install a listener, you need to know the event source You add an event listener object to selected event sources: Examples: OK Button clicked, Cancel Button clicked, Menu Choice… Whenever the event occurs, the event source calls the appropriate methods of all attached event listeners 12 Example ActionListener The ActionListener interface has one method: public interface interface ActionListener ActionListener public {{ void actionPerformed(ActionEvent actionPerformed(ActionEvent event); event); void }} ClickListener class implements the ActionListener interface We can ignore the event parameter – it has information such as when the event occurred. 13 Registering ActionListener A ClickListener object must be created, and then ‘registered’ (added) to a specific event source ActionListener listener listener == new new ClickListener(); ClickListener(); ActionListener button.addActionListener(listener); button.addActionListener(listener); Now whenever the button object is clicked, it will call listener.ActionPerformed, passing it the event as a parameter 14 ButtonFrame1.java Creates and adds a JButton to the frame. Tells the button to ‘call us back’ when an event occurs. 15 ButtonViewer1.java No changes required to the main to implement an event handler 16 Inner Classes for Listeners In the preceding section, you saw how the code that is executed when a button is clicked is placed into a listener class. Inner classes are often used for ActionListeners An inner class is a class that is declared inside another class It may be declared inside or outside a method of the class Why inner classes? Two reasons: 1) It places the trivial listener class exactly where it is needed, without cluttering up the remainder of the project 2) Their methods can access variables that are declared in surrounding blocks In this regard, inner classes declared inside methods behave similarly to nested blocks 17 Example Inner Class Listener The inner class ClickListener declared inside the class ButtonFrame2 can access local variables inside the surrounding scope Outer Block Inner Block public class class ButtonFrame2 ButtonFrame2 extends extends JFrame JFrame public {{ private JButton JButton button; button; private private JLabel JLabel label; label; private .. .. .. class ClickListener ClickListener implements implements ActionListener ActionListener class {{ public void void actionPerformed(ActionEvent actionPerformed(ActionEvent event) event) public {{ label.setText("I was was clicked"); clicked"); label.setText("I }} Can easily access methods of the }} . . . private instance of a label object. . . . } } 18 ButtonFrame2.java (1) 19 ButtonFrame2.java (2) 20 InvestmentFrame.java (1) 21 InvestmentFrame.java (2) User clicks the button four times for output: 22 Processing Text Input Dialog boxes allows for user input… but Popping up a separate dialog box for each input is not a natural user interface Most graphical programs collect text input through text fields The JTextField class provides a text field When you construct a text field, supply the width: The approximate number of characters that you expect If the user exceeds this number, text will ‘scroll’ left final int int FIELD_WIDTH FIELD_WIDTH == 10; 10; final final JTextField JTextField rateField rateField == new new JTextField(FIELD_WIDTH); JTextField(FIELD_WIDTH); final 23 Add a Label and a Button A Label helps the user know what you want Normally to the left of a textbox JLabel rateLabel rateLabel == new new JLabel("Interest JLabel("Interest Rate: Rate: "); "); JLabel A button with an actionPerformed method can be used to read the text from the textbox with the getText method Note that getText returns a String, and must be converted to a numeric value if it will be used in calculations double rate rate == Double.parseDouble(rateField.getText()); Double.parseDouble(rateField.getText()); double double interest interest == account.getBalance() account.getBalance() ** rate rate // 100; 100; double account.deposit(interest); account.deposit(interest); resultLabel.setText("balance: "" ++ account.getBalance()); account.getBalance()); resultLabel.setText("balance: 24 InvestmentFrame2.java (1) Use this as a framework for GUIs that do calculations Place input components into the frame. 25 InvestmentFrame2.java (2) Do calculations in ActionPerformed method Keep the code for the listener and the object (Button) in the same area 26 Text Areas Create multi-line text areas with a JTextArea object Set the size in rows and columns final int int final final int int final JTextArea JTextArea ROWS == 10; 10; ROWS COLUMNS == 30; 30; COLUMNS textArea == new new JTextArea(ROWS, JTextArea(ROWS, COLUMNS); COLUMNS); textArea Use the setText method to set the text of a text field or text area textArea.setText(“Account Balance”); Balance”); textArea.setText(“Account 27 Text Areas The append method adds text to the end of a text area Use newline characters to separate lines textArea.append(account.getBalance() ++ "\n"); "\n"); textArea.append(account.getBalance() Use the setEditable method to control user input textArea.setEditable(false); textArea.setEditable(false); 28 JTextField and JTextArea JTextField and JTextArea inherit from JTextComponent: setText setEditable 29 JTextField and JTextArea The append method is declared in the JTextArea class To add scroll bars, use JScrollPane: JScrollPane scrollPane scrollPane == new new JScrollPane(textArea); JScrollPane(textArea); JScrollPane 30 InvestmentFrame3.java (1) Declare the components to be used 31 InvestmentFrame3.java (2) Constructor calls methods to create the components 32 InvestmentFrame3.java (3) The listener class and associated createButton method 33 Creating Drawings You cannot draw directly on a JFrame object Instead, construct an object and add it to the frame A few examples objects to draw on are: JComponent Jpanel JTextComponent JLabel public class class chartComponent chartComponent extends extends JComponent JComponent public {{ public void void paintComponent(Graphics paintComponent(Graphics g) g) public {{ // Drawing Drawing instructions instructions go go here here // }} Extend the JComponent Class and }} override its paintComponent method 34 The paintComponent Method The paintComponent method is called automatically when: The component is shown for the first time Every time the window is resized, or after being hidden public class class chartComponent chartComponent extends extends JComponent JComponent public {{ public void void paintComponent(Graphics paintComponent(Graphics g) g) public {{ g.fillRect(0, 10, 10, 200, 200, 10); 10); g.fillRect(0, g.fillRect(0, 30, 30, 300, 300, 10); 10); g.fillRect(0, g.fillRect(0, 50, 50, 100, 100, 10); 10); g.fillRect(0, } } } } 35 ChartComponent.java We now have a JComponent object that can be added to a Jframe The Graphics class is part of the java.awt package 36 ChartViewer.java Adding the component to the frame 37 The Graphics Parameter The paintComponent method receives an object of type Graphics The Graphics object stores the graphics state The current color, font, etc., that are used for drawing operations The Graphics2D class extends the Graphics class Provides more powerful methods to draw 2D objects When using Swing, the Graphics parameter is actually of the Graphics2D type, so we need to cast it to Graphics2D to use it public class class RectangleComponent RectangleComponent extends extends JComponent JComponent public {{ public void void paintComponent(Graphics paintComponent(Graphics g) g) public {{ Graphics2D g2 g2 == (Graphics2D) (Graphics2D) g; g; Graphics2D }} Now you are ready to draw more complex shapes! }} 38 Ovals, Lines, Text, and Color Ellipses are drawn inside a bounding box in the same way that you specify a rectangle: Provide the x and y coordinates of the top-left corner Provide the width and height of the bounding box Use the Graphics class drawOval method to create an ellipse g.drawOval(x, y, y, width, width, height); height); g.drawOval(x, Use drawLine between two points: g.drawLine(x1, y1, y1, x2, x2, y2); y2); g.drawLine(x1, 39 Drawing Text Use the drawString method of the Graphics class to draw a string anywhere in a window Specify the String Specify the Basepoint (x and y coordinates) The Baseline is the y coordinate of the Basepoint g2.drawString("Message", 50, 50, 100); 100); g2.drawString("Message", 40 Using Color All shapes and strings are drawn with a black pen and white fill by default To change the color, call setColor with an object of type Color Java uses the RGB color model You can use predefined colors, or create your own g.setColor(Color.YELLOW); g.setColor(Color.YELLOW); g.fillOval(350, 25, 25, 35, 35, 20); 20); g.fillOval(350, All shapes drawn after setColor will use it 41 ChartComponent2.java 42 Application: Investment Growth Input the interest rate Click on the ‘Add Interest’ button to add bars to the graph Maintains a list of values to redraw all bars each time 43 ChartComponent.java (1) Use an ArrayList to hold bar values Add a new value to ArrayList 44 ChartComponent.java (2) Paint bars in a loop 45 InvestmentFrame4.java (1) Instantiates and initializes ChartComponent Use helper methods to create components 46 InvestmentFrame4.java (2) Listener and Button setup 47 Steps to Drawing Shapes 1) Determine the shapes you need for your drawing. Squares and rectangles Circles and ellipses Lines and text 2) Find the coordinates of each shape. For rectangles and ellipses, you need the top-left corner, width, and height of the bounding box. For lines, you need the x- and y-positions of the starting point and the end point. For text, you need the x- and y-position of the basepoint 48 Steps to Drawing Shapes 3) Write Java statements to draw the shapes. g.setColor(Color.GREEN); g.setColor(Color.GREEN); g.fillRect(100, 100, 100, 30, 30, 60); 60); g.fillRect(100, g.setColor(Color.RED); g.setColor(Color.RED); g.fillRect(160, 100, 100, 30, 30, 60); 60); g.fillRect(160, 10.4 Creating Creating Drawings Drawings 499 499 10.4 g.setColor(Color.BLACK); g.setColor(Color.BLACK); g.drawLine(130, 100, 100, 160, 160, 100); 100); g.drawLine(130, g.drawLine(130, 160, 160, 160, 160, 160); 160); g.drawLine(130, If possible, use variables and ‘offsets’ for the locations and sizes g.fillRect(xLeft, yTop, yTop, width width // 3, 3, width width ** 22 // 3); 3); g.fillRect(xLeft, .. .. .. g.fillRect(xLeft ++ 22 ** width width // 3, 3, yTop, yTop, width width // 3, 3, width width ** 22 // 3); 3); g.fillRect(xLeft .. .. .. g.drawLine(xLeft ++ width width // 3, 3, yTop, yTop, xLeft xLeft ++ width width ** 22 // 3, 3, yTop); yTop); g.drawLine(xLeft 49 Steps to Drawing Shapes 4) Consider using methods or classes for repetitive steps. void drawItalianFlag(Graphics drawItalianFlag(Graphics g, g, int int xLeft, xLeft, int int yTop, yTop, int int width) width) void {{ // Draw Draw aa flag flag at at the the given given location location and and size size // }} 5) Place the drawing instructions in the paintComponent method. public class class ItalianFlagComponent ItalianFlagComponent extends extends JComponent JComponent public {{ public void void paintComponent(Graphics paintComponent(Graphics g) g) public {{ // Drawing Drawing instructions instructions // }} }} If the drawing is complex, use call methods of Step 4 50 Steps to Drawing Shapes 6) Write the viewer class. Provide a viewer class, with a main method in which you construct a frame, add your component, and make your frame visible. public class class ItalianFlagViewer ItalianFlagViewer public {{ public static static void void main(String main(String args) args) public {{ JFrame frame frame == new new JFrame(); JFrame(); JFrame frame.setSize(300, 400); 400); frame.setSize(300, frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent component component == new new ItalianFlagComponent(); ItalianFlagComponent(); JComponent frame.add(component); frame.add(component); frame.setVisible(true); frame.setVisible(true); }} } } 51 Summary Implement simple graphical user interfaces Add buttons, text fields, and other components to a frame window Handle events that are generated by buttons Write programs that display simple drawings 52 ...
View Full Document

  • Fall '19
  •  EXAMPLES

{[ snackBarMessage ]}

Get FREE access by uploading your study materials

Upload your study materials now and get free access to over 25 million documents.

Upload now for FREE access Or pay now for instant access
Christopher Reinemann
"Before using Course Hero my grade was at 78%. By the end of the semester my grade was at 90%. I could not have done it without all the class material I found."
— Christopher R., University of Rhode Island '15, Course Hero Intern

Ask a question for free

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern