Download 19/09/2016 COMPSCI230 Agenda Swing Pluggable look

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
19/09/2016
Agenda

Swing – AWT’s successor






CompSci 230 S2 2016
Software Construction
GUI Component
Swing and threads
Painting
Graphics2D
Other Controls
Reading

Using Swing Components

Laying Out Components Within a Container

Writing Event Listeners

Swing
Craig Sutherland, [email protected]


2
Swing


http://docs.oracle.com/javase/tutorial/uiswing/events/index.html




2
COMPSCI 230
Pluggable look and feel

A richer set of GUI components, many of which are located in package
javax.swing

3
http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html
Swing is a more complex and powerful successor to the AWT
Swing includes:


http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
By convention, Swing component names are prefixed by J (e.g. JButton, JLabel etc.) and
are subclasses of JComponent, which is a subclass of the AWT’s Component class
Windows Look
Components that have separate models; the Swing framework originates
from the Model-View-Control (MVC) paradigm
Components that have a pluggable look-and-feel
Cosmetic improvements – e.g. buttons and labels can show images rather
than just text, and components can be decorated with a variety of borders
Swing’s painting model improves the AWT’s but is slightly more complex
Swing uses the AWT’s layout management and event handling
infrastructure
Data : Time value

Digital Clock
Analog Clock
Motif Look
( used on Linux)
Having separate data andimport
state javax.swing.*;
models makes the Swing components
highly customizable, and enables
data sharing between components
Buttons on Digital Clock
Knobs on Back of Analog Clock
4
COMPSCI230

COMPSCI 230
Example: SwingDemo1.java
SwingDemo2.java, SwingDemo3.java
The Swing framework
allows, with minimal effort,
any Swing application to
take on the look-and-feel of
particular windowing
systems
A Swing GUI can also switch
to a different look-and-feel
at runtime
Note: Do not mix Swing and
AWT in the same window
19/09/2016
In principle, all GUI elements
are in the Component class
Swing Overview

Top-Level Containers
Most Swing components are lightweight: formed by drawing in the underlying
window

Lightweight Components

Component
Container
Components that are software only


Object
JComponent
JScrollPane

JPopupMenu
JList
JPanel

JFrame

Component
Container
Window
Dialog
Frame
JDialog
JFrame
5
JApplet


Components that have system-dependant peers (they integrate the Java components with the
local system’s native code)
Object


Many other
classes
Heavyweight Components

Root
Top level of the "containment hierarchy"
Swing applications with GUI will have at least one top-level
container (contains all of the Swing components)
Frames are the simplest and most commonly used containers
A standard GUI based application will typically contain at least one frame
JDialog


Panel
A class that enable applets to use Swing components
A dialog box is just like a dialog box in Windows
Usually used to display warning messages, help the user or ask for information


Applet

JColorChooser
JFileChooser
JOptionPane

JApplet
has many options for different types of dialog boxes
JWindow
COMPSCI 230
6
COMPSCI 230
Example: HelloSwing.java
Richer components
JFrame
JTabbedPane

JFrame – top level Container


JToolBar



JSplitPane
JSlider

JSpinner
Components should be added to the content pane rather than the frame
The java system creates a content pane automatically while initializing.The
content pane can be obtained with the function getContentPane()
The Default layout manager is BorderLayout and default look is Metal
Use setVisible(true) to display the frame on the screen
Use pack() to pack or setSize(…) to set the size
JFrame closes automatically when you click on the close button. However,
closing the last JFrame does not result in the program exiting the Java
application



JTree
JTable
import javax.swing.*;
To exit the application
Use WindowListener to call System.exit(0), OR
Use EXIT_ON_CLOSE
...
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
7
8
COMPSCI 230
COMPSCI230
COMPSCI 230
19/09/2016
Example: HelloSwing.java
Swing and threads



createAndShowGUI()
Most Swing components are not thread-safe.
 Threads run at the same time. Problems arise if one thread
alters things in another thread, without them being
synchronised.
 Need to be careful!
Solution is to make sure all code that creates and modifies
Swing components executes in the same 'event-dispatching'
thread
Start a Swing application using the following code..


All the code to set up and start the GUI is placed in the static
method createAndShowGUI
Steps:






Quit the application when the frame is closed
Add components to the content pane
frame.pack()
frame.setVisible(true)
private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
public static void main (String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUIClass().createAndShowGUI();
}
});
}
9
Construct a JFrame (a GUI window) with a title.
frame.setDefaultCloseOperation()
}
COMPSCI 230
10
COMPSCI 230
Example: TempConvGUI.java
Example: SwingPaintDemo.java
A Simple Swing App


The Paint Methods - Swing
Responding to user actions by using a JOptionPane
JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something:

Same rules to AWT’s component

except that Swing further factors the paint() call into three
separate methods, which are invoked in the following order:

showConfirmDialog:




Asks a confirming question, like yes/no/cancel.

showInputDialog:


showMessageDialog :

showOptionDialog:



Prompt for some input.

Tell the user about something that has happened.
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
Swing programs should override paintComponent() instead of
overriding paint().
void paintComponent(Graphics g) {
Dimension size = getSize();
int x = 0;
int y = 0;
int i = 0;
while(x < size.width && y < size.height) {
g.setColor(i%2==0? Color.red : Color.white);
g.fillOval(x,y,size.width-(2*x),size.height-(2*y));
x+=10; y+=10; i++;
}
The Grand Unification of the above three.
fahrString = JOptionPane.showInputDialog("Enter the temperature in F");
fahr = Double.parseDouble(fahrString);
cel = (fahr - 32) * 5.0/9.0;
JOptionPane.showMessageDialog(null,"The temperature in C is, " + cel);
11
paint() gets called when it's time to render
COMPSCI 230
12
COMPSCI230
COMPSCI 230
19/09/2016
Example: SwingMouseMain.java
Component
Painting in Swing
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JPanel mousePanel = new
MousePositionJPanel();
add( mousePanel );
}
setBounds( 100, 100, 200, 200 );
setVisible( true );
}
public static void main( String[ ] args ) {
SwingMouseMain mouseMain = new
SwingMouseMain( );
}
}
public void paint ( Graphics g ) {
paintComponent( g );
// Code to paint border.
}
public void paintComponent( Graphics g ) {
// Code to paint the background.
}
JComponent
paintComponent( g : Graphics )
public MousePositionJPanel( ) {
mouseX = 100;
mouseY = 100;
public SwingMouseMain( ) {
super( "MouseListener Demo" );
}
paint( g : Graphics ) : void
repaint( ) : void
class MousePositionJPanel extends JPanel {
private int mouseX, mouseY;
public class SwingMouseMain extends JFrame {
<< interface >>
MouseListener
public void paintComponent( Graphics g ) {
// Code to paint a panel’s background.
}
JPanel
addMouseListener( new MouseAdapter( ) {
public void mousePressed( MouseEvent e ) {
mouseX = e.getX( );
mouseY = e.getY( );
repaint( );
}
} );
public void paintComponent( Graphics g ) {
// Make sure the background is painted.
super.paintComponent( g );
MousePositionJPanel
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
g.drawString( "(" + mouseX + ", " + mouseY + ")", mouseX, mouseY );
}
// Now do custom painting.
g.drawString ( "(" + mouseX + ", " + mouseY + ")",
mouseX, mouseY );
For custom painting in Swing, JComponent subclasses should override paintComponent( ) (and, in general,
make a super.paintComponent( ) call).
JComponent subclasses should not generally override paint( ) or repaint( ).
13
14
COMPSCI 230
COMPSCI 230
Run-time call stack for painting a
MousePositionJPanel instance
JPanel.paintComponent( )
MousePositionJPanel.paintComponent( ) MousePositionJPanel.paintComponent( )
JComponent.paint( )
JComponent.paint( )
JComponent.paint( )
(1)
(2)
(3)
Graphics & Graphics2D
Graphics.drawString( )
MousePositionJPanel.paintComponent( )

(4)
Old graphics context: java.awt.Graphics

JComponent.paint( )

New graphics context: java.awt.Graphics2D

MousePositionJPanel.paintComponent( )
(1)
(2)
(3)
(4)
(5)
(6)
15

JComponent.paint( )
JComponent.paint( )
(5)
(6)

The paint( ) message sent to a MousePositionJPanel object is bound to JComponent’s paint( )
method.
JComponent’s paint( ) method calls paintComponent( ), which is bound to class MouseMotionPanel’s
paintComponent( ) method.
MouseMotionPanel’s paintComponent( ) method calls it’s superclasses’ paintComponent( ) method
causing JPanel’s paintComponent( ) method to be executed.
Control returns to MousePositionJPanel’s paintComponent( ) method which then calls drawString(
) on a Graphics instance; class Graphics’ drawString method is executed.
Control returns to MousePositionJPanel’s paintComponent( ) method which then terminates
execution.
Control returns the JComponent’s paint( ) method which then also terminates, completing the
painting process.
COMPSCI 230
Used in Java 1.0 and 1.1, now obsolete
Part of Java 2D (in Java 1.2 and later)
Although paintComponent() takes a Graphics object, what you get is
really a Graphics2D!
Basic methods for painting (Graphics and Graphics2D):





drawLine()
clearRect(), drawRect(), draw3DRect(), fillRect(), fill3DRect()
drawArc(), fillArc(), drawOval(), fillOval()
drawPolygon(), fillPolygon(), drawPolyLine()
drawString()
public void paintComponent(final Graphics g) {
final Graphics2D g2d = (Graphics2D) g; // Just cast it…
// Use g2d
}
16
COMPSCI230
COMPSCI 230
19/09/2016
Example: MenuDemo.java
Java 2D
Basic Controls
Support for arbitrary shapes





A single draw() method, a single fill()
Draws or fills anything implementing



With text and/or graphic labels
Create an ImageIcon

ImageIcon saveIcon = createImageIcon("save.gif");
JButton saveButton = new JButton("Save", saveIcon);
saveButton.setMnemonic(KeyEvent.VK_S);
Line2D, Rectangle2D, RoundRectangle2D
Arc2D, Ellipse2D
QuadCurve2D, CubicCurve2D
...

JButton
Alt-S
Pen styles implement the Stroke interface (BasicStroke)





Color: Solid fill, default color space sRGB (rgb + alpha)

Color.RED, Color.GREEN, Color.BLACK, ...



17
COMPSCI 230
Basic Controls


A JComboBox, which lets the user choose one of several choices, can have two very different
forms :uneditable combo box (a button and a drop-down list of values) or editable
JPanel






Method: void actionPerformed(ActionEvent e)
Use getSelectedItem



19
JScrollPane


Event: ListSelectionListener

Create a Border object by calling BorderFactory
Use setBorder() to set the border
leftPanel.setBorder(BorderFactory.createTitledBorder("Left"));
A JList presents the user with a group of items to choose from.
Lists can have many items, so they are often put in scroll panes.
list = new Jlist<String>(petStrings);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

Add other components inside using add() (can contain other JPanels)
The default layout is “BorderLayout”
Border

String petName = petList.getSelectedItem().toString();
output.append(petName);
JList


Event: ActionListener
Example: BorderDemo.java
A second-level container used to hold components within a top-level container such
as a frame or a dialog

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
petList = new JComboBox<String>(petStrings);

menuItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
output.append("click a menu ");
}
});
General-Purpose Containers
JComboBox

It can contain menus, menu items, radio button menu items, check box menu items, and separators.

Use setPaint() or the older setColor()
saveButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
output.append("Save ");
}
Anonymous Inner class
});
A menu usually appears either in a menu bar or as a popup menu.
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("A Menu");
menuBar.add(menu);
JMenuItem menuItem =
new JMenuItem("A Menu Item");
menu.add(menuItem);
setJMenuBar(menuBar);
18
TexturePaint: Tiles a picture (repeats as necessary)
GradientPaint: A gradient between two colors

Use ActionListener
JMenu
Color cyan2 = new Color(0, 255, 255); // Between 0 and 255

Handling event

Fill patterns implement the Paint interface

protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ToolBarDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL); ...
Mnemonics: keyboard accelerators that let you use Alt+someChar to trigger the button

Different line widths, patterns, join styles
Use setStroke()
Finds a resource (image
file) with a given name
Method: void valueChanged(ListSelectionEvent e)
Use getSelectedValue
list.addListSelectionListener( new ListSelectionListener() {
Provides a scrollable view of a component
Used to view a portion of a component that is too large to fit
JScrollPane s = new JScrollPane( component_to_be_scrolled );
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) { //No selection
output.append("No selection");
} else { //Selection
output.append(list.getSelectedValue().toString());
...
20
COMPSCI230
COMPSCI 230
TitledBorder
EtchedBorder
19/09/2016
Example: SplitPaneDemo.java
General-Purpose Containers

JSplitPane

Displays two components, either side by side or above each other
JButton left = new JButton("Left Button" );
JButton right = new JButton("Right Button");
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
split.setOneTouchExpandable(true);
split.setDividerLocation(50);

JToolBar

Acts basically like a JPanel for buttons
JToolBar toolBar = new JToolBar();
21
COMPSCI 230
COMPSCI230