340 likes | 349 Views
Java classes in review. … or, what you should have learned in school, had you been paying attention. Terminology. Program Object Class Method Variable Argument Parameter. Anatomy of a Java program. A (non-empty) set of classes containing: At least one member method
E N D
Java classes in review … or, what you should have learned in school, had you been paying attention
Terminology • Program • Object • Class • Method • Variable • Argument • Parameter
Anatomy of a Java program • A (non-empty) set of classes containing: • At least one member method • 0 or more member variables and/or constants • Problem: The CS1 syndrome! • Most real programs do not consist of one method (main) using one or more simple algorithms to solve a problem • A pure OOP approach would describe a Java program as a set of interacting objects • How do objects interact?
Graphics programming & Java • Java comes with two extensive libraries of classes and objects for graphical programming • AWT • Swing • Most of these classes are designed to facilitate GUI programming • JFrame class describes a GUI window • JOptionPane class provides GUI interface for I/O • Sample program that follows illustrates use of these classes
Example import java.awt.*; import javax.swing.*; public class WindowEx { private JFrame win; public WindowEx(int wd, int ht) { win = new JFrame(); win.setSize(wd, ht); win.setTitle("Here's your window"); win.setVisible(true); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
Example continued public static void main (String [] args) { WindowEx window; String input; int num1, num2; input = JOptionPane.showInputDialog(null, "Enter width of window: "); num1 = Integer.parseInt(input); input = JOptionPane.showInputDialog(null, "Enter length of window: "); num2 = Integer.parseInt(input); window = new WindowEx(num1, num2); } }
Method types • Constructors • Accessors • Mutators (modifiers) • What is the effect of the keyword “static” when applied to a method?
Drawing pictures • A class can be defined to create a customized JFrame object via the inheritance mechanism • The Graphics class includes methods for drawing simple geometrical shapes • A paint() method for a JFrame window takes a Graphics parameter which can be used to draw a picture in the window
Swing objects and the paint() method • Most Swing components include a paint() method, which is used to draw the component on the screen • This method is inherited from JComponent, an ancestor class for most of the Swing objects • As an inherited method, we have been able to use it (invisibly, since none of our code has called it directly) without modifying, or overriding the original version • In order to draw our own pictures, we will need to provide a new paint() definition, overriding the original
The paint() method • The paint method for an object is automatically invoked when the object is made visible; there is almost never an explicit call to the method • The paint() method has a single parameter of type Graphics, typically named g • We use g to invoke the methods that draw pictures
Example public class BlueSquare extends JFrame { // instance variables describe position & size of square private int x = 20, y = 40, size = 100; // constructor not shown – just sets size & location of JFrame public void paint (Graphics g) { g.setColor(Color.BLUE); g.fillRect(x,y,size,size); } public static void main (String[] args) { BlueSquare b = new BlueSquare(); b.setVisible(true); } }
Example • The code from the previous slide (along with the constructor and main method) produces this result: • The 100 x 100 pixel square is placed within a 140 x 160 window with its upper left corner at position (20, 40)
Graphics drawing methods • Shape drawing methods include: • drawRect – rectangle outline • drawOval – ellipse outline • fillRect – filled rectangle • fillOval – filled ellipse • Each takes four int arguments • 1st and 2nd: x,y coordinates of bounding rectangle’s upper left corner • 3rd and 4th: width and length of figure
Graphics drawing methods • drawRoundRect and fillRoundRect: rectangles with rounded corners • First 4 arguments to these are the same as for the rectangle methods • 2 additional int arguments specify the width and height of the corner arcs
Graphics drawing methods • drawLine: draws a line between two points specified by 4 int arguments: • 1st and 3rd arguments are the x coordinates • 2nd and 4th are the y coordinates
Graphics drawing methods • drawArc and fillArc: draw partial ellipses within bounding rectangles; each takes 6 int arguments: • 1st and 2nd: xy position of upper left corner of bounding rectangle • 3rd and 4th: width and height of bounding rectangle • 5th: start of drawing arc (number between 0 and 359) • 6th: sweep of drawing arc (number of degrees of arc sweep) • A positive sweep value draws arc in clockwise direction • A negative sweep value draws arc in counterclockwise direction
The repaint() method • The paint() method is called automatically when a window is made visible • If changes need to be made to the window’s appearance, the window must be redrawn • This operation is accomplished by the repaint() method
Adding components to a JFrame • The previous program example displayed a window with simple shape objects • We can place GUI objects, such as buttons, text areas or sliders in a JFrame window by using the add method, as shown in the next example
import javax.swing.*; import java.awt.*; public class JFrameEx2 extends JFrame { private JButton aButton; public JFrameEx2() { aButton = new JButton(“Click Me”); setTitle("I've been framed!"); setSize(300, 200); setLocation(150, 250); setDefaultCloseOperation(EXIT_ON_CLOSE); add (aButton); } public static void main(String[] args) { JFrameEx2 frame = new JFrameEx2(); frame.setVisible(true); } } Code at left produces the window shown below: You can click the button, but it doesn’t do anything; there is no action listener attached to the button to handle the action event that is created
Buttons that listen • In order for a button to be functional, it must have an action listener associated with it • Each button object possesses an addActionListener method which can be used to make the association • The addActionListener method takes an ActionListener object as its argument • An ActionListener object is an instance of a class that implements the ActionListener interface
The ActionListener Interface • An interface in Java is something like a class with methods specified but not defined • A class that implements an interface provides the definition(s) for any specified method(s) • The ActionListener interface has one method specified: public void actionPerformed(ActionEvent e)
JFrame with working button import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JFrameEx3 extends JFrame implements ActionListener { private JButton aButton; public JFrameEx3 () { aButton = new JButton(“Click Me”); aButton.addActionListener(this); setTitle("I've been framed!"); setSize(300, 200); setLocation(150, 250); setDefaultCloseOperation(EXIT_ON_CLOSE); add(aButton); }
… continued from previous slide public void actionPerformed (ActionEvent e) { aButton.setText(“Thanks”); } public static void main(String[] args) { JFrameEx3 frame = new JFrameEx3(); frame.setVisible(true); } } Before click: After:
Notes on example • The example illustrates some of the principles of event-driven programming discussed earlier • Note that, although the actionPerformed method exists, and we can see that it performs its action, it is never explicitly called anywhere in the program • Keep in mind that an event object is like an exception object: • it only gets created under certain circumstances • like a catch block that matches an exception, the actionPerformed method is invoked automatically when its matching event object appears
More notes on example • In the example, the class defined (JFrameEx3) both inherited from parent class JFrame (using the extends mechanism) and implemented the ActionListener interface • In the first couple of examples in the text, a separate class is defined to implement ActionListener • In either case, the only requirement of a class that implements the interface is that the class provides a definition for the actionPerformed method
Even more notes on example • The reason for having the example class implement the interface was so that the actionPerformed method would have access to the JButton object and its setText method • Note that a third import statement had to be added to the program to make the ActionListener interface available: import java.awt.event.*;
JPanel objects • A JFrame makes a good overall container, as it has all of the attributes we have come to expect in a window • However, a JFrame contained within a JFrame would be overkill; a better option would be an unadorned window, with just a content pane and no frame or title bar • Such a window can be created with a JPanel object • A single JFrame can contain several JPanels
Example • The next example illustrates the use of this hierarchical layout scheme • The main window is split into two panels (display and buttonArea), which are arranged in the main window using the BorderLayout manager • The buttonArea has a FlowLayout manager attached to it, and it contains a single component, a JButton • The code fragment on the next slide contains that portion of the constructor where the layout managers and components are added; the class and method heading, as well as instructions that set up the main window are omitted for brevity
Example pane = getContentPane(); // content pane of main windowpane.setLayout(new BorderLayout()); // layout manager for main window display = new JPanel(); // upper portion of window: displays colordisplay.setBackground(getNewColor()); // starts with random colorpane.add(display, BorderLayout.CENTER); control = new JButton ("CHANGE IT!"); // button to change to new colorcontrol.addActionListener(this); buttonArea = new JPanel(); // lower portion of window: holds buttonbuttonArea.setLayout(new FlowLayout());buttonArea.setBackground(Color.BLACK);buttonArea.add(control); pane.add(buttonArea, BorderLayout.SOUTH);
Example continued public Color getNewColor() { // returns a new color constructed randomly Random rg = new Random(); int r, g, b; r = rg.nextInt(256); g = rg.nextInt(256); b = rg.nextInt(256); return new Color(r,g,b);}public void actionPerformed (ActionEvent e) { // changes color when // button is activated display.setBackground(getNewColor());} public static void main (String [] args) { ColorPanel06 demo = new ColorPanel06(); demo.setVisible(true);}
Complete program produces output like the examples shown below