+ All Categories
Home > Documents > Java GUIs and Graphics CNS 3250. Outline Introduction Events Components Layout managers Drawing...

Java GUIs and Graphics CNS 3250. Outline Introduction Events Components Layout managers Drawing...

Date post: 31-Dec-2015
Category:
Upload: ashlie-lyons
View: 234 times
Download: 0 times
Share this document with a friend
40
Java GUIs and Graphics CNS 3250
Transcript

Java GUIs and GraphicsJava GUIs and Graphics

CNS 3250CNS 3250

OutlineOutline

Introduction Events Components Layout managers Drawing

Introduction Events Components Layout managers Drawing

GUIs and graphics in JavaGUIs and graphics in Java

Portable! Listeners and events Components Layout managers

Portable! Listeners and events Components Layout managers

A design considerationA design consideration

Data components should exist independently from GUI components They should have no knowledge of GUI

GUI components call upon data objects for information

Why is this a good approach to use?

Data components should exist independently from GUI components They should have no knowledge of GUI

GUI components call upon data objects for information

Why is this a good approach to use?

HistoryHistory

AWT / Event Model (JDK 1.1) Heavyweight components

Use OS “peers”

Event Dispatch Thread Listeners to handle events

Swing (Java 2) Lightweight components

Painted via graphics (not OS peers) Preserves look and feel across platforms

AWT / Event Model (JDK 1.1) Heavyweight components

Use OS “peers”

Event Dispatch Thread Listeners to handle events

Swing (Java 2) Lightweight components

Painted via graphics (not OS peers) Preserves look and feel across platforms

EventsEvents

How does your program know if the user clicks something with the mouse?

Register a listener object. When the user clicks with the mouse, the system passes an event object to the listener.

How does your program know if the user clicks something with the mouse?

Register a listener object. When the user clicks with the mouse, the system passes an event object to the listener.

ListenersListeners

Implements one of the listener interfaces: ActionListener MouseListener MouseMotionListener WindowListener etc.

Listener interfaces are defined in java.awt.event

Implements one of the listener interfaces: ActionListener MouseListener MouseMotionListener WindowListener etc.

Listener interfaces are defined in java.awt.event

ActionListener interfaceActionListener interface

Used with buttons, menu items, text fields Only one method, actionPerformed

Takes an ActionEvent object as parameter

ActionEvent has a method that tells the command that triggered the name of the event. For a button, the text of the button will be the

command by default.

Used with buttons, menu items, text fields Only one method, actionPerformed

Takes an ActionEvent object as parameter

ActionEvent has a method that tells the command that triggered the name of the event. For a button, the text of the button will be the

command by default.

Red Alert!Red Alert!

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

class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton;

public RedAlert() {redAlertButton = new JButton("Red Alert");add(redAlertButton);redAlertButton.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!");}

}

public static void main(String[] args) {RedAlert frame = new RedAlert();frame.setSize(200, 100);frame.setVisible(true);

}}

Red Alert!Red Alert!

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

class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton;

public RedAlert() {redAlertButton = new JButton("Red Alert");add(redAlertButton);redAlertButton.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!");}

}

public static void main(String[] args) {RedAlert frame = new RedAlert();frame.setSize(200, 100);frame.setVisible(true);

}}

MouseListenerMouseListener

Includes several methods: mouseClicked mouseEntered mouseExited mousePressed mouseReleased

Includes several methods: mouseClicked mouseEntered mouseExited mousePressed mouseReleased

Each method gets a MouseEvent object that tells the coordinates of the mouse and other info.

All methods have to be defined, whether you use them or not...

Each method gets a MouseEvent object that tells the coordinates of the mouse and other info.

All methods have to be defined, whether you use them or not...

MouseAdapterMouseAdapter

Defines all required methods for the MouseListener interface

Methods are empty. Override the methods you actually want to

use. Use by making your class extend MouseAdapter.

Defines all required methods for the MouseListener interface

Methods are empty. Override the methods you actually want to

use. Use by making your class extend MouseAdapter.

AdaptersAdapters

All methods for the corresponding listener interface are defined.

Only useful if your class doesn't need to inherit from any other class.

Commonly used for mouse listeners, mouse motion listeners, window listeners.

There is no adapter for action listeners.

Why not?

All methods for the corresponding listener interface are defined.

Only useful if your class doesn't need to inherit from any other class.

Commonly used for mouse listeners, mouse motion listeners, window listeners.

There is no adapter for action listeners.

Why not?

Using listeners and eventsUsing listeners and events

Decide what kind of listener you need This is usually based on the kind of input and

the type of component you will be using

Define a class for that kind of listenerMake a class that implements the interface

Make a class that extends an adapter

Register the listener with the component add____Listener, e.g. addActionListener

Decide what kind of listener you need This is usually based on the kind of input and

the type of component you will be using

Define a class for that kind of listenerMake a class that implements the interface

Make a class that extends an adapter

Register the listener with the component add____Listener, e.g. addActionListener

or

Red Alert!Red Alert!

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

class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton;

public RedAlert() {redAlertButton = new JButton("Red Alert");add(redAlertButton);redAlertButton.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!");}

}

public static void main(String[] args) {RedAlert frame = new RedAlert();frame.setSize(200, 100);frame.setVisible(true);

}}

PolyDraw demoPolyDraw demo

Elf -- Java Ldraw displayElf -- Java Ldraw displayUses OpenGL (JOGL)Uses OpenGL (JOGL)

POV-Ray -- Ray tracingPOV-Ray -- Ray tracing

ComponentsComponents

Top-level containers General-purpose containers Displays Controls Text components

Top-level containers General-purpose containers Displays Controls Text components

http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

Top-level containersTop-level containers

Every Java GUI program must have a top-level container. Frame (AWT--java.awt) JFrame (Swing--javax.swing)

Every Java GUI program must have a top-level container. Frame (AWT--java.awt) JFrame (Swing--javax.swing)

http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

General-purpose containersGeneral-purpose containers

Panel(AWT)

JPanel(Swing)

Panel(AWT)

JPanel(Swing)

http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

JPanel -- very commonly usedJPanel -- very commonly used

Container for components DrawingContainer for components Drawing

DisplaysDisplays

JLabel Can include an image in addition to (or instead of

text) Can use HTML formatting

JLabel Can include an image in addition to (or instead of

text) Can use HTML formatting

ControlsControls JButton

JComboBox

JList

JMenuItem

JButton

JComboBox

JList

JMenuItem

What listeners and events?What listeners and events?

ControlsControls JButton

JComboBox

JList

JMenuItem

JButton

JComboBox

JList

JMenuItem

What listeners and events?What listeners and events?

ActionEvent

PopupMenuEvent

ActionEvent

PopupMenuEvent

ListSelectionEventListSelectionEvent

ActionEventActionEvent

ActionEventActionEvent

Text componentsText components

http://java.sun.com/docs/books/tutorial/uiswing/components/text.html

JTextAreaJTextArea

Used for multi-line text display and editing Does not handle scrolling internally (as

TextArea does) Add to JScrollPane to get scrolling Implements Scrollable interface

Can specify whether or not editing is allowed

Can specify line wrapping or not

Used for multi-line text display and editing Does not handle scrolling internally (as

TextArea does) Add to JScrollPane to get scrolling Implements Scrollable interface

Can specify whether or not editing is allowed

Can specify line wrapping or not

JEditorPaneJEditorPane

Can display HTML Not a "speed demon" according to our text

book Can get very complicated

Can display HTML Not a "speed demon" according to our text

book Can get very complicated'<html><body bgcolor="GRAY"> <center> <img src="$BASE$MapPics/castle1.png"> <h3>Castle</h3> </center> A castle stands on a hill here. It doesn\'t appear to be inhabited, but it\'s hard to say for sure. <br></body></html>'

PolyDraw componentsPolyDraw components

JScrollPane

JPanel

JButton

JTextField

JLabel

JFrame

JMenuBarJMenu

JMenuItem JPanel

JComboBox

Layout managersLayout managers

Where should components go?

Usually: x, y coordinates.

In Java location, size, and shape of components depends on another question:

How big will the user's display be? Could be anything from a huge, high-res

display to a cell phone Can change

Where should components go?

Usually: x, y coordinates.

In Java location, size, and shape of components depends on another question:

How big will the user's display be? Could be anything from a huge, high-res

display to a cell phone Can change

Good news, bad newsGood news, bad news

Good news Adjusts components to fit size/shape of

container Can write Java GUIs with no special tools Works well for different fonts, languages

Bad news Can be difficult to get what you want Unexpected results

Good news Adjusts components to fit size/shape of

container Can write Java GUIs with no special tools Works well for different fonts, languages

Bad news Can be difficult to get what you want Unexpected results

Types of layout managersTypes of layout managers

BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SpringLayout

BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SpringLayout

Pictures on the following slides are from the Java Tutorial:

http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html

Using a layout managerUsing a layout manager

Create (or get access to) container Set layout manager for container Create component Add component to container

Create (or get access to) container Set layout manager for container Create component Add component to containerContainer cp = getContentPane();cp.setLayout(new BorderLayout());JButton button = new JButton("Button 1");cp.add(button, BorderLayout.CENTER);

These steps vary somewhat depending on the layout manager.

BorderLayoutBorderLayout

Very commonly used The center area grows/shrinks the most Regions are (or used to be):

Center, North, South, East, West

Very commonly used The center area grows/shrinks the most Regions are (or used to be):

Center, North, South, East, West

BoxLayoutBoxLayout

Relatively new Fillers:

strut--1D fixed amount of space rigid area--2D fixed amount of space glue--variable amount of space, separates

components as much as possible

(Textbook says "spring" would be a better term than "glue".)

Relatively new Fillers:

strut--1D fixed amount of space rigid area--2D fixed amount of space glue--variable amount of space, separates

components as much as possible

(Textbook says "spring" would be a better term than "glue".)

CardLayoutCardLayout

Used to switch back and forth between different layouts in the same space

Usually need to keep a reference to the layout manager object so that you can control which card is showing.

Used to switch back and forth between different layouts in the same space

Usually need to keep a reference to the layout manager object so that you can control which card is showing.

FlowLayoutFlowLayout

The simplest layout manager Can specify horizontal alignment

The simplest layout manager Can specify horizontal alignment

GridBagLayoutGridBagLayout

Very flexible, but very complicated See the p. 433 in Core Java Vol. I for a

"Recipe for Making a Grid Bag Layout" Note Step 7: "compile, run, and enjoy"

Must create GridBagConstraints objects Book recommends a helper class GBC

NetBeans and other IDEs offer visual tools

Very flexible, but very complicated See the p. 433 in Core Java Vol. I for a

"Recipe for Making a Grid Bag Layout" Note Step 7: "compile, run, and enjoy"

Must create GridBagConstraints objects Book recommends a helper class GBC

NetBeans and other IDEs offer visual tools

GridLayoutGridLayout

Useful for a number of components that are the same size

Position is determined by order that components are added to the container

Useful for a number of components that are the same size

Position is determined by order that components are added to the container

SpringLayoutSpringLayout

Meant to be as flexible as GridBagLayout but "more intuitive"

It might be as flexible, but I think it's safe to say that it isn't more intuitive.

Meant to be as flexible as GridBagLayout but "more intuitive"

It might be as flexible, but I think it's safe to say that it isn't more intuitive.


Recommended