CS102 – GUI Based on : David Davenport’s slides Spring 2002 References: .

89
CS102 – GUI Based on : David Davenport’s slides Spring 2002 References: http://java.sun.com/docs/books/tutorial/uiswing http://www.aduni.org/courses/java Core Java Volume 1 http://www.javaworld.com/javaworld/jw-04-1998/jw-04- howto.html
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    220
  • download

    1

Transcript of CS102 – GUI Based on : David Davenport’s slides Spring 2002 References: .

Page 1: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

CS102 – GUI

Based on :David Davenport’s slidesSpring 2002References:http://java.sun.com/docs/books/tutorial/uiswinghttp://www.aduni.org/courses/javaCore Java Volume 1http://www.javaworld.com/javaworld/jw-04-1998/jw-04-howto.html

Page 2: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Swing

is implemented without making use of native window elements

components are painted by java on blank windows.

more flexibility, not the lowest common denominator

same look, same bugs in all platforms The Swing components will continue to be

enhanced in the future, AWT is dying

Page 3: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Programming forms

Procedural programming code is executed in sequential order.

Event-driven programming code is executed upon activation of events.

statement 1statement 2statement 3 -------- --------statement n

method 1method 2method 3 -------- --------method n

Do method 1

then method 3

Do method 2

then method 1

thenmethod 3

Page 4: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

procedural programming

Up to now, our control flow model has been pretty straight-forward.

Execution starts at main() and executes statement sequentially branching with if,for,and while statement, and occasional method calls.

When we need user input we call read() on the console stream which waits (blocks) until the user types something, then returns.

One problem with this model is: How do we wait for and respond to input from more than one source (eg keyboard and mouse). If we block on either waiting for input, we may miss input from the other.

Page 5: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Event-driven programming

the system waits for user input events, and these events trigger program methods

Event-based programming addresses the two problems: How to wait on multiple input sources

(input events) How to decide what to do on each type

of input event

Page 6: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

General form of event-driven programming

The operating system and window system process input event from devices (mouse movement, mouse clicks, key presses etc)

The window system decides which window, and hence which frame and program, each input event belongs to.

A data structure describing the event is produced and placed on an 'event queue'. Events are added to one end of the queue by the window system . Events are removed from the queue and processed by the program. These event data structures hold information including: Which of the program's windows this event belongs

to. The type of event (mouse click, key press, etc.) Any event-specific data (mouse position, key code,

etc.)

Page 7: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Event loop

main(){ ...set up application data structures... ...set up GUI.... // enter event loop while(true){ Event e = get_event(); process_event(e); // event dispatch routine } }

the event loop is usually hidden from programmer, he/she provides just a process_event() method

Page 8: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

AWT Applications - Frame

Frame is a container for components

Frame with normal window

controlsOptional Menu

Three containers in Frame with

Border Layout

UI-components inside

containers each with own layout

Page 9: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Understanding the GUI

UI-containers have list of

UI-components

Each UI-component is a class with paint method & lists of

Event listeners

{Frame}

{label}

{textfield}

{button}

components

Page 10: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Setting up the GUI

Extend Frame class In constructor

• Create instances of containers& add them to Frame

• Create instances of components& add them to containers or Frame

Possibly override paint method

UI-components added to components list Painting Frame

1.paints Frame borders2.calls Frame paint method3.calls paint method of each object in component list

Hint: Employ layout managers

to arrange components in

containers

Page 11: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

A simple example

import javax.swing.*;

class FirstFrame extends JFrame { public FirstFrame() { setTitle("FirstFrame"); setSize(300, 200); }}

public class FirstTest { public static void main(String[] args) { JFrame frame = new FirstFrame(); frame.show(); }}

Page 12: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Simple Example Remarks

we have two classes, one for the frame, the other for the main method that creates the frame

we could have put the main method inside class FirstFrame

if we don’t set the size, the default is a window of size 0x0

java runtime creates a new thread for our frame

it doesn’t terminate, just hides

Page 13: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Hello World Program

import javax.swing.*; public class HelloWorldSwing {

public static void main(String[] args) { JFrame frame = new JFrame("HelloWorld"); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setBounds(200, 200, 200, 50);frame.setVisible(true);

} }

Page 14: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Containers

Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet.

To appear onscreen, every GUI component must be part of a containment hierarchy. Each containment hierarchy has a top-level container as its root.

Each top-level container has a content pane that, generally speaking, contains the visible components in that top-level container's GUI.

You can optionally add a menu bar to a top-level container. The menu bar is positioned within the top-level container, but outside the content pane.

Page 15: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Container Tree

• a frame, or main window (JFrame) • a panel, sometimes called a

pane (JPanel) •a button (JButton) •a label (JLabel)

                                              

                                        

    

Page 16: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Containers ..

The frame is a top-level container. It exists mainly to provide a place for other Swing components to paint themselves.

The panel is an intermediate container. Its only purpose is to simplify the positioning of the button and label. Other intermediate Swing containers, such as scroll panes (JScrollPane) and tabbed panes (JTabbedPane), typically play a more visible, interactive role in a program's GUI.

The button and label are atomic components -- components that exist not to hold random Swing components, but as self-sufficient entities that present bits of information to the user. Often, atomic components also get input from the user.

Page 17: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Layouts

Page 18: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using Layout Managers

By default, every container has a layout manager.

All JPanel objects use a FlowLayout by default, whereas content panes (the main containers in JApplet, JDialog, and JFrame objects) use BorderLayout by default.

You can change the layout as: JPanel pane = new JPanel(); pane.setLayout(new

BorderLayout()); When you add components to a panel or a

content pane, the arguments you specify to the add method depend on the layout manager that the panel or content pane is using.

Page 19: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout

A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.

Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding a component to a container with a border layout, use one of these five constants, for example: Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Button("Okay"), BorderLayout.SOUTH);

Page 20: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout Example

Container contentPane = getContentPane(); //Use the content pane's default BorderLayout.//contentPane.setLayout(new BorderLayout()); contentPane.add(new JButton("Button 1 (NORTH)"),

BorderLayout.NORTH); contentPane.add(new JButton("2 (CENTER)"),

BorderLayout.CENTER); contentPane.add(new JButton("Button 3 (WEST)"),

BorderLayout.WEST); contentPane.add(new JButton("Long-Named Button 4

(SOUTH)"), BorderLayout.SOUTH);contentPane.add(new JButton("Button 5 (EAST)"),

BorderLayout.EAST);

Page 21: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout Output

Page 22: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout cont. We specified the component as the first argument to

the add method. For example: add(component, BorderLayout.CENTER) //preferred However, you might see code in other programs that specifies the component second. For example, the following are alternate ways of writing the preceding code: add(BorderLayout.CENTER, component) add("Center", component) //valid but error prone

By default, a BorderLayout puts no gap between the components it manages. You can specify gaps (in pixels) using the following constructor: BorderLayout(int horizontalGap, int verticalGap) You can also use the following methods to set the horizontal and vertical gaps, respectively: void setHgap(int) void setVgap(int)

Page 23: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

BorderLayout(20, 20)

Page 24: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout Resizing

First North and South are drawn with their normal sizes, then east & west, finally all the rest of the space is reserved for center.

center is the default location by default anything in center fill

resize to fill the space

Page 25: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Border Layout Resized

Page 26: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Flow Layout

FlowLayout puts components in a row, sized at their preferred size.

If the horizontal space in the container is too small to put all the components in one row, FlowLayout uses multiple rows.

Within each row, components are centered (the default), left-aligned, or right-aligned as specified when the FlowLayout is created.

Page 27: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Flow Layout Example

Container contentPane = getContentPane();contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1"));contentPane.add(new JButton("2"));contentPane.add(new JButton("Button 3"));contentPane.add(new JButton("Long-Named

Button 4"));contentPane.add(new JButton("Button 5"));

Page 28: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Flow Layout Example Output

Page 29: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

The FlowLayout API

The FlowLayout class has three constructors: public FlowLayout() public FlowLayout(int alignment) public FlowLayout(int alignment, int horizontalGap, int

verticalGap)

The alignment argument must have the value FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT.

The horizontalGap and verticalGap arguments specify the number of pixels to put between components. If you don't specify a gap value, FlowLayout uses 5 for the default gap value.

Page 30: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Grid Layout

A GridLayout places components in a grid of cells.

Each component takes all the available space within its cell, and each cell is exactly the same size.

If you resize the GridLayout window, it changes the cell size so that the cells are as large as possible, given the space available to the container.

Page 31: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Grid Layout Example

Container contentPane = getContentPane();contentPane.setLayout(new GridLayout(0,2));contentPane.add(new JButton("Button 1"));contentPane.add(new JButton("2"));contentPane.add(new JButton("Button 3"));contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));

The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary.

Page 32: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Grid Output

Page 33: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

The GridLayout API

The GridLayout class has two constructors: public GridLayout(int rows, int columns)

public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) At least one of the rows and columns arguments

must be nonzero. The horizontalGap and verticalGap arguments to

the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero.

Page 34: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Why Layouts?

Can use Absolute Layout Layouts provide flexibility in

different environments with different screen resolutions.

Font sizes, component contents may change (internationalization)

Page 35: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Events & Event Handling

Example… User clicks on a button Button is source of event object Event object passed to associated listener object Listener object executes associated method

to perform desired task (save file, quit program, …)

Eventlistenerobject

(executesmethod)

EventObjectEvent

cause(mouse,

keyboard, timer, …)

EventSourceobject

Page 36: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Setting up Event Handling

Create listener class Using new or existing class, simply Implement desired event listener interface Putting code for desired action in its methods

In application (e.g. Frame)

Create instance of listener class Add as listener of source object

• can have any number of listeners for each event• Source & listener can be same object!

Page 37: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Understanding Events

When button is pressed actionPerformed method

of every item in button’s actionListeners list called

Similarly for textfield When Frame close button

is pressed windowClosing method of

every item in Frame’s windowListeners list called

{Frame}

{label}

{textfield}

{button}

components

ActionListeners

ActionListenersactionPerformed

{MyListener}

actionPerformed

WindowListeners

windowClosing

Page 38: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Event Classes

AWTEvent EventObject

AdjustmentEvent

ComponentEvent

TextEvent

ItemEvent

ActionEvent

InputEvent

WindowEvent

MouseEvent

KeyEvent

ContainerEvent

FocusEvent

PaintEvent

ListSelectionEvent

Page 39: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Event Examples

User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener

User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a

component MouseListener User moves the mouse over a component

MouseMotionListener Component becomes visible ComponentListenerComponent gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

Page 40: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

How to Implement an Event Handler

In the declaration for the event handler class, specify that the class either implements a listener interface or extends a class that implements a listener interface. For example:

public class MyClass implements ActionListener { Register an instance of the event handler class as a

listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass)

Implement the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

Page 41: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

public class MC extends JFrame implements ActionListener { private int noClicks = 0; private JButton button = new JButton("click me !"); private JTextArea textArea = new JTextArea(5, 40); private JLabel label = new JLabel("Here you can see the

number of button clicks") ; private JProgressBar progressBar =

new JProgressBar(JProgressBar.HORIZONTAL);

public MC(String title) { super(title); Container cp = getContentPane(); cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS)); cp.add(button); JScrollPane scrollPane = new JScrollPane(textArea); cp.add(scrollPane);cp.add(label); cp.add(progressBar); button.addActionListener(this); }

Page 42: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Action Example Cont.

public void actionPerformed(ActionEvent e) { noClicks++; textArea.append("Button clicked " + noClicks +

" times so far \n"); label.setText("You clicked " + noClicks + " times"); progressBar.setValue(noClicks); } public static void main(String[] args) { MyClass frame = new MyClass("Simple Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } }

Page 43: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Mouse Click Examplepublic class MouseClick extends JFrame implements MouseListener { private JLabel statusBar; public MouseClick() { statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); addMouseListener( this ); //listens own mouse and setSize(300,300); setVisible(true); } public void mouseClicked(MouseEvent event) { statusBar.setText("Clicked at [" + event.getX() + ", " + event.getY() + "]"); } public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {}

public static void main(String[] args) { MouseClick application = new MouseClick(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

Page 44: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Listener Class Flavors

public class MyClass implements MouseListener { ... someObject.addMouseListener(this); ...

public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {

...//Event handler implementation goes here...

} }

Page 45: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Adapter Classes

Java comes with a variety of adapter classes that implement Listener interfaces but have empty implementations.

One can extend an adapter class and only override events that are of interest

Page 46: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Adapter Example

An example of extending an adapter class instead of directly implementing a listener interface.

public class MyClass extends MouseAdapter { ... x.addMouseListener(this); ...

public void mouseClicked(MouseEvent e) { //Event handler implementation

// goes here... } }

Page 47: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using an Inner class …

What if your class has to extend another one? public class MyClass extends Applet { ... x.addMouseListener(new MyAdapter());...

class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) {

...//Event handler implementation // goes here... }

} }

Page 48: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using an Anonymous Inner class

public class MyClass extends Applet { ... x.addMouseListener( new MouseAdapter() {

public void mouseClicked(MouseEvent e) { ...//Event handler impl.

}

}); ... } } an inner class can refer to instance

variables and methods just as if its code is in the containing class

Page 49: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Exampleclass PanelJ2 extends JPanel {

public PanelJ2() { JButton b = new JButton( "OK"); setLayout( new BorderLayout() ); setBackground( Color.red); add( b, BorderLayout.SOUTH); b.addActionListener( new ExampleActionListener()); }

// restores screen after window has been covered, minimized, public void paintComponent( Graphics g) {

super.paintComponent( g); g.drawRect( 50, 50, 200, 100); g.drawString( "Hello", 125, 100 ); }}

Page 50: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Action Listener

class ExampleActionListener implements ActionListener {

public void actionPerformed( ActionEvent e) {

System.out.println( "Button Pressed"); }}

Page 51: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Putting 3 of PanelJ2 …

class MyJFrame extends JFrame {

public MyJFrame() { Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( new PanelJ2()); c.add( new PanelJ2()); c.add( new PanelJ2()); setTitle( "ExampleJ3 - Hi there"); setBounds( 100, 150, 300, 300); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setVisible(true); }}

Page 52: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Outcome …

Page 53: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Put them inside an applet

public class AppletExample extends Applet {

public void init() { setLayout( new FlowLayout() ); add( new PanelJ2()); add( new PanelJ2()); add( new PanelJ2()); }

}

Page 54: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Applet outcome

Page 55: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Which button ?

Let’s say you have three buttons on your application. How can you tell which button was pressed?

We need something distinct about the event object to decide what to do

We can use getSource() method

Page 56: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

ButtonPanel

class ButtonPanel extends JPanel implemnts ActionListener{  public ButtonPanel() { 

yellowButton = new JButton("Yellow");      blueButton = new JButton("Blue");      redButton = new JButton("Red"); 

      add(yellowButton);      add(blueButton);      add(redButton); 

      yellowButton.addActionListener(this);       blueButton.addActionListener(this);       redButton.addActionListener(this);    } 

   private JButton yellowButton, blueButton, redButton;} 

Page 57: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

actionPerformed method

   public void actionPerformed(ActionEvent evt){  Object source = evt.getSource();

      Color color = getBackground();      if (source == yellowButton) color = Color.yellow;      else if (source == blueButton) color = Color.blue;      else if (source == redButton) color = Color.red;      setBackground(color);      repaint();   } 

Page 58: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

An alternative?

We used the same listener object for all the buttons (ButtonPanel itself)

Another approach would be to use different listeners who knows about what they should do when the event happens

Page 59: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

ColorAction inner class

private class ColorAction implements ActionListener {

public ColorAction(Color c) { backgroundColor = c; }

public void actionPerformed(ActionEvent event) { setBackground(backgroundColor); }

private Color backgroundColor; }

Page 60: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

New constructor …

public ButtonPanel() { // create buttons JButton yellowButton = new JButton("Yellow"); . . .

// add buttons to panel add(yellowButton); add(blueButton); add(redButton);

// create button actions ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED);

// associate actions with buttons yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); }

Page 61: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

ColorAction, another aproach

class ColorAction implements ActionListener { public ColorAction(Color c, JPanel p) { backgroundColor = c;

buttonPanel = p; } public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } private Color backgroundColor; private JPanel buttonPanel;

}

Page 62: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

The program ..

Page 63: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Drawing Shapes

public class Triangle1 extends JFrame { public static final int SIZE = 100;

public void paint (Graphics g) { int sqrt3size = (int) (SIZE*Math.sqrt(3));

g.drawLine(SIZE, SIZE/2, 3*SIZE/2, SIZE/2+ sqrt3size/2); g.drawLine(3*SIZE/2, SIZE/2+ sqrt3size/2, SIZE/2, SIZE/2+

sqrt3size/2 ); g.drawLine(SIZE, SIZE/2, SIZE/2, SIZE/2+ sqrt3size/2 ); } public static void main(String[] args) { JFrame jf = new Triangle1(); jf.setSize(300, 300); jf.setVisible(true); }}

Page 64: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using JPanel…public class Triangle2 extends JFrame { public static void main(String[] args) {

JFrame jf = new JFrame();jf.getContentPane().add(new TrianglePanel());jf.setSize(300, 300);jf.setVisible(true);

}}

class TrianglePanel extends JPanel { public static final int SIZE = 100; public void paintComponent(Graphics g) {

super.paintComponent(g);drawTriangle(g);

}

private void drawTriangle(Graphics g) {int sqrt3size = (int) (SIZE*Math.sqrt(3));g.drawLine(SIZE, SIZE/2, 3*SIZE/2, SIZE/2+ sqrt3size/2);g.drawLine(3*SIZE/2, SIZE/2+ sqrt3size/2, SIZE/2, SIZE/2+ sqrt3size/2 );g.drawLine(SIZE, SIZE/2, SIZE/2, SIZE/2+ sqrt3size/2 );

}}

Page 65: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using two components…public class Triangle3 extends JFrame { public Triangle3() {

getContentPane().add(new TrianglePanel(), BorderLayout.CENTER);getContentPane().add(new JLabel("Triangle Demo"), BorderLayout.SOUTH);setSize(300, 300);setVisible(true);

} public static void main(String[] args) {

new Triangle3(); }}

class TrianglePanel extends JPanel { public static final int SIZE = 100; public void paintComponent(Graphics g) {

super.paintComponent(g);drawTriangle(g);

}

Page 66: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Putting more Options..

Page 67: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

A Hierarchy of Shapes..abstract class Shape { static final int DEFAULT_SIZE = 100; int size; public void setSize(int size) {

this.size = size; } abstract public void draw(Graphics g);}

class Triangle extends Shape { public void draw(Graphics g) {

… }}

class Square extends Shape { public void draw(Graphics g) {

g.drawRect(size/2, size/2, size, size); } }

class Circle extends Shape { public void draw(Graphics g) {

g.drawOval(size/2, size/2, size, size); }}

Page 68: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Shape Panel

class ShapePanel extends JPanel { Shape currentShape; public void setShape(Shape shape) {

currentShape = shape; } public void paintComponent(Graphics g) {

super.paintComponent(g);if (currentShape != null)

currentShape.draw(g); }}

Page 69: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

public class Shapes extends JFrame { JTextField sizeInput = new JTextField(3); JButton triangleButton = new JButton("Draw Triangle"); JButton squareButton = new JButton("Draw Square"); JButton circleButton = new JButton("Draw Circle"); ShapePanel shapePanel = new ShapePanel(); public Shapes() {

JPanel sizePanel = new JPanel();sizePanel.add(new JLabel("Size"));sizePanel.add(sizeInput);

JPanel buttonPanel = new JPanel();buttonPanel.add(triangleButton);buttonPanel.add(squareButton);buttonPanel.add(circleButton);

JPanel topPanel = new JPanel();topPanel.setLayout(new GridLayout(2, 1));topPanel.add(sizePanel);topPanel.add(buttonPanel);

//shapePanel.setSize(200, 200);shapePanel.setPreferredSize(new Dimension(200, 200));getContentPane().add(topPanel, BorderLayout.NORTH);getContentPane().add(shapePanel, BorderLayout.CENTER);pack();setVisible(true);

Page 70: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Setting Up the Events…ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) {

int size = Integer.parseInt(sizeInput.getText());Shape shape;if (e.getSource() == triangleButton) shape = new Triangle();else if (e.getSource() == squareButton) shape = new Square();else shape = new Circle();

shape.setSize(size);shapePanel.setShape(shape);repaint();

}};triangleButton.addActionListener(listener);squareButton.addActionListener(listener);circleButton.addActionListener(listener);

}

Page 71: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Generating Random Circles

Page 72: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

class CirclesPanel extends JPanel { ArrayList<Circle> circles = new ArrayList<Circle>();

public void addCircle() { circles.add(new Circle()); } public void paintComponent (Graphics page) { super.paintComponent(page); for (Circle c : circles) { page.drawOval(c.x, c.y, c.radius, c.radius ); } }}

class Circle { int x, y; int radius; static Random random = new Random();

public Circle() { x = random.nextInt(400); y = random.nextInt(400); radius = random.nextInt(20) + 3; }}

Page 73: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

public class Circles extends JFrame { CirclesPanel circlesPanel = new CirclesPanel();

public Circles() { JButton button = new JButton("Click me");

button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { circlesPanel.addCircle(); repaint(); }

} ); getContentPane().add(button, BorderLayout.SOUTH); getContentPane().add(circlesPanel, BorderLayout.CENTER); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }

public static void main(String[] args) { new Circles(); }}

Page 74: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Using a Timerpublic class Circles2 extends JFrame { CirclesPanel circlesPanel = new CirclesPanel();

public Circles2() { ///JButton button = new JButton("Click me"); Timer timer = new Timer(10, null);

timer.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { circlesPanel.addCircle(); repaint(); }

} ); //getContentPane().add(button, BorderLayout.SOUTH); getContentPane().add(circlesPanel, BorderLayout.CENTER); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

timer.start(); setVisible(true); }…

Page 75: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Mouse Listener Example

public class MouseMove extends JFrame { private Rectangle box; private int x,y; public static void main(String[] args) { MouseMove m = new MouseMove(); } public MouseMove() { super("Mouse Demonstration"); Container cp=getContentPane(); JPanel mousePanel = new MousePanel(); mousePanel.setPreferredSize(new Dimension(300, 300)); cp.add(mousePanel); pack(); setVisible(true); }}

Page 76: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

class MousePanel extends JPanel { int x,y; public MousePanel() { addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent event) { x=event.getX(); y=event.getY(); System.out.println(event); repaint(); } } ); }

public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("You clicked here", x, y); } }

Page 77: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Video and CD Database

Page 78: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Video, CD Example

Let’s write a program based on Video, CD and Database classes earlier.

Write a program that lets user enter CD or Video Details and shows a listing of the items already entered

Page 79: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

Snapshot of the program

Page 80: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

TextEntry

Note that most of the GUI consists of getting a text value from user.

There is a prompt telling user what to enter

We can write a class for this purpose

Page 81: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

TextEntryclass TextEntry extends JPanel{

private JTextField field = new JTextField();

public TextEntry(String prompt) {setLayout(new GridLayout(1,2));add(new JLabel(prompt));add(field);

}

public String getValue() {return field.getText ();

}}

Page 82: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

IntEntry

Sometimes, we get an integer value from user.

Hopefully, the process of getting a text and integer from user is very similar, we can reuse the TextEntry class

Page 83: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

IntEntry

class IntEntry extends TextEntry {public IntEntry(String prompt) {

super(prompt);}

public int getIntValue() {return Integer.parseInt(getValue());

}}

Page 84: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

The panel for entering CDs and the panel for entering Videos are also similar.

We can collect the common elements in a separate class

Page 85: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

abstract class ItemPanel extends JPanel implements ActionListener{TextEntry title = new TextEntry("Enter the title");IntEntry playingTime = new IntEntry("Enter the playing time");ItemListing listing;

public ItemPanel(String ptitle, ItemListing listing) {this.listing = listing;setLayout(new GridLayout(0,1));setBorder(BorderFactory.createTitledBorder (ptitle));add(title);add(playingTime);

}

public abstract Item getItem();

public void actionPerformed(ActionEvent ae) {listing.addItem (getItem());

}}

Page 86: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

CDPanelclass CDPanel extends ItemPanel {

TextEntry artist = new TextEntry("Enter the artist ");IntEntry nTracks = new IntEntry("Enter the number of tracks ");

public CDPanel(ItemListing listing) {super("CD Entry", listing);add(artist);add(nTracks);JButton button = new JButton("Create the CD");button.addActionListener(this);add(button);

}

public Item getItem() {return new CD(title.getValue(), artist.getValue (),

nTracks.getIntValue (), playingTime.getIntValue ());}

}

Page 87: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

VideoPanelclass VideoPanel extends ItemPanel {

TextEntry director = new TextEntry("Enter the director ");

public VideoPanel(ItemListing listing) {super("Video Entry", listing);add(director);JButton button = new JButton("Create the Video");button.addActionListener(this);add(button);

}

public Item getItem() {return new Video(title.getValue(),

director.getValue(),playingTime.getIntValue ());}

}

Page 88: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

class ItemListing {JTextArea text;Database database;

public ItemListing(JTextArea text, Database database) {this.text = text;this.database = database;

}

public void addItem(Item item) {database.addItem (item);text.setText (database.toString());

}}

Page 89: CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:  .

public class CollectionFrame extends JFrame{VideoPanel videoPanel;CDPanel cdPanel;Database database = new Database();JTextArea listing = new JTextArea(10,30);

public CollectionFrame () {ItemListing itemListing = new ItemListing(listing, database);videoPanel = new VideoPanel(itemListing);cdPanel = new CDPanel(itemListing);

Container cp = getContentPane();cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));

JPanel entryPanel = new JPanel();entryPanel.add(cdPanel);entryPanel.add(videoPanel);cp.add(entryPanel);

JScrollPane sp = new JScrollPane(listing);cp.add(sp);

pack();setVisible(true);