Java Swing
December 8, 2016 | Author: Nguyễn Đức Thành | Category: N/A
Short Description
Download Java Swing...
Description
Concurrent Programming
Java Swing
Introduction to Java Swing Swing and Threads (Applets and Java 2D graphics)
2.04.2009
Outline • Introduction to Swing • Components and Containers • Anatomy of an Application • Layouts • Event Processing • Swing and Threads • Model View Controller concept • Appendix (if we have time) • Applets • Java 2D graphics
http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html
2
How to Learn Swing • Don’t even try. • Learn framework principles and design styles. • Use the API reference, and Swing Tutorials to discover detailed usage of each component. Java Documentation http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/package-summary.html
SwingSet - examples http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html
Tutorial http://java.sun.com/docs/books/tutorial/uiswing/index.html
3
Java Foundation Classes • Abstract Window Toolkit (AWT) • original user interface toolkit • don’t go there! import java.awt.*; import java.awt.event.*; • Swing (package javax.swing.*) • Includes everything from buttons to split panes to tables • The look and feel of Swing applications is pluggable • Supports Internationalization (Japanese, Chinese, or Korean) import javax.swing.*; import javax.swing.event.*;
Swing vs. AWT • Never mix Swing and AWT components • If you know AWT, put ‘J’ in front of everything • AWT: Button • Swing: JButton • Swing does all that AWT does, but better and there is something more.
(c) O’Reilly 1999
5
Swing Standard GUI components buttons, lists, menus, and text areas Containers such as windows and tool bars. ¾ ¾
top level: frames, dialogs intermediate level: panel, scroll pane, tabbed pane, ...
An index of Swing components http://java.sun.com/docs/books/tutorial/uiswing/index.html
6
Top-Level Containers
http://java.sun.com/docs/books/tutorial/ui/features/components.html
7
Containers Notes: ¾ Container objects group components, arranging them for display with a layout manager.
containers
8
General-Purpose Containers
9
Basic Controls
10
Components
The essential Swing components
AWT Swing
11
Example 1 import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); pack() causes a window to frame.setVisible(true); be sized to fit the } preferred size and layouts of its sub-components }
Example 2 import javax.swing.*;
In this example a custom frame is created
public class HelloWorldFrame extends JFrame { public HelloWorldFrame() { super(“HelloWorldSwing”); final JLabel label = new JLabel("Hello World"); getContentPane().add(label); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public static void main(String[] args) { HelloWorldFrame frame = new HelloWorldFrame(); } }
Build from bottom up Create: Frame Panel Components
JLabel
JButton
Add: (bottom up) listeners into components components into panel panel into frame
JPanel
JFrame
Layout Managers Organizing Layout of components in a container null
FlowLayout
none, programmer sets x,y,w,h
Left to right, Top to bottom
BorderLayout n w
c s
e
CardLayout
One at a time
GridLayout
GridBagLayout
JButton
Combinations
JButtonJButton
JTextArea
Combinations
JButton
JButton
JFrame n
JPanel: FlowLayout
JPanel: BorderLayout c JTextArea
Code: null layout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null); // x,y layout p.add(b); f.setContentPane(p); press me
Code: FlowLayout JFrame f = JPanel p = FlowLayout JButton b1 JButton b2
new JFrame(“title”); new JPanel( ); L = new FlowLayout( ); = new JButton(“press me”); = new JButton(“then me”);
p.setLayout(L); p.add(b1); p.add(b2); f.setContentPane(p); Set layout mgr before adding components
press me then me
import java.awt.*; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame f = new JFrame("title"); JPanel p = new JPanel( ); FlowLayout L = new FlowLayout( ); JButton b1 = new JButton("press me"); JButton b2 = new JButton("then me"); p.setLayout(L); p.add(b1); p.add(b2); f.setContentPane(p); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } }
20
Box Layout http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html
myPane.setLayout(new BoxLayout(myPane, BoxLayout.PAGE_AXIS)); Component.CENTER_ALIGNMENT
Component.LEFT_ALIGNMENT
Component.RIGHT_ALIGNMENT
21
A simple Swing program - Events Events • objects communicate by “firing” and “handling” events • events are sent from a single source object to one or more registered listener objects
2 2
Types of Event Listeners
Act that results in event
Listener type
User clicks a button, presses Return while typing in a ActionListener text field, or chooses a menu item User closes a frame (main window)
WindowListener
User presses a mouse button while the cursor is over MouseListener a component User moves the mouse over a component
MouseMotionListener
Component becomes visible
ComponentListener
Component gets the keyboard focus
FocusListener
Table or list selection changes
ListSelectionListener
Events Handling: ¾ create a component e.g., a JButton ¾
add it to the GUI
Listener JLabel
JButton
e.g., to a JPanel ¾
register a listener to be notified when the component generates an event
JPanel
e.g., interface ActionListener ¾
define the callback method e.g., actionPerformed()
JFrame
24
Event Handling class MyListener implements ActionListener { … public void actionPerformed( ActionEvent event ) { // react to event … } } …
// instantiate event listener ActionListener listener = new MyListener(); … // instantiate event source JButton button = new JButton( “Hello” ); … // register event listener with event source button.addActionListener( listener );
25
Example using local class
button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } } );
JDialog Every dialog is dependent on a frame A dialog can be modal. When a modal dialog is visible it blocks user input to all other windows in the program.
• To create custom dialogs, use the JDialog class directly. • Swing provides several standard dialogs ¾ JProgressBar, JFileChooser, JColorChooser, ...
Dialog Example •
The JOptionPane class can be used to create simple modal dialogs (icons, title, text and buttons can be customized). Object[] options = {"Yes", "No",
"I don't know"};
int n = JOptionPane.showOptionDialog( frame, "You are listening about Swing \n" + "Do you already think Java?", "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
Swing and Threads Swing components are NOT Thread safe • The signgle-thread rule • Once a Swing component has been realized (A Swing component that’s a top level windows is realized by having one of these methods invoked on it: setVisible(), show(), or pack()), all code that might affect or depend on the state of that component should be executed in the eventdispatching thread. • Exception to the rule: A few operations are guaranteed to be thread-safe.
29
Safe Swing code public class Stuff implements EventListener { public JFrame frame; public JButton button; public Stuff() { button = new Button(); ... Unsafe to update frame = new Jframe(); state of Swing frame.add(button); components ... frame.setVisible(true); ... Safe to update } state of Swing public void someMethod() { components ... } public void actionPerformed(ActionEvent event) { ... } }
Event Dispatching • To access to the UI from outside event-handling or drawing code. • SwingUtilities.invokeLater() requests that some code be executed in the event-dispatching thread. This method returns immediately, without waiting for the code to execute. • SwingUtilities.invokeAndWait() acts as invokeLater(), but waits for the code to execute. javax.swing.SwingUtilities.invokeLater( new Runnable(){ public void run(){ // Access to components } } );
31
Handle a job in the background • If you need to create a thread – for example, to handle a job that’s computationally expensive or I/O bound – you can use a thread utility class such as SwingWorker or Timer. • SwingWorker creates a background thread to execute time-consuming operations. • Timer creates a thread that executes some code one or more times, with a user-specified delay between executions
32
Model/View/Controller
from Krasner and Pope
http://www.itu.dk/courses/VOP/E2005/VOP2005E/8_mvc_krasner_and_pope.pdf
33
Model/View/Controller
MVC roles: ¾ model complete, self-contained representation of object managed by the application e.g., spreadsheet document provides a number of services to manipulate the data e.g., recalculate, save computation and persistence issues ¾…
try to separate the model and its services so that it is Swing-free
34
Model/View/Controller MVC roles: ¾ view tracks what is needed for a particular perspective of the data e.g., bar chart view presentation issues ¾ controller
gets input from the user, and uses appropriate information from the view to modify the model e.g., get slider value, trigger chart modify interaction issues in practice, views and controllers are implemented with Swing components and listeners 35
Model/View/Controller
Separation: ¾ you can modify or create views without affecting the underlying model ¾ the
model should not need to know about all the kinds of views and interaction styles available for it
36
MVC
as seen by Sun
37
Pluggable Look and Feel Each picture shows the same program but with a different look and feel
Pluggable Look-and-Feel Swing: • the look-and-feel is implemented in Java, but could mimic Windows, Motif, Classic, Aqua, etc. • UIManager.setLookAndFeel( “com.sun.java.swing.plaf.windows.WindowsLookAndFeel” ); • UIManager.setLookAndFeel( “javax.swing.plaf.metal.MetalLookAndFeel” ); http://java.sun.com/docs/books/tutorial/ui/overview/demo.html
39
Extra part • Applets • Graphics
40
Applets JApplet is like a JFrame Already has a panel
JApplet
Access panel with JApplet.getContentPane( )
import javax.swing.*;
contentPane
class Hello extends JApplet { JButton public void init(){ JButton b = new JButton(“press me”); getContentPane().add(b); } }
Applet Methods Called by browser: init( ) start( ) stop( ) destroy( ) paint( )
- initialization - resume processing (e.g. animations) - pause - cleanup - redraw stuff (‘expose’ event)
Application + Applet import javax.swing.*; class helloApp { public static void main(String[] args){ Command line JFrame f = new JFrame(“title”); mainPanel p = new mainPanel(); f.setContentPane(p); f.show(); } JFrame or } class helloApplet extends JApplet { public void init(){ mainPanel p = new mainPanel(); getContentPane().add(p); } } class mainPanel extends JPanel { mainPanel(){ setLayout(new FlowLayout()); JButton b = new JButton(“press me”); add(b); } }
Browser
JApplet
contentPane
JPanel JButton
Applet Security No read/write on client machine Can’t execute programs on client machine Communicate only with server “Java applet window” Warning
Java 2D API
Graphics • Complex drawing and shading API. • Can do far more than display images.
4 5
Graphics Window is like a painter’s canvas App must paint its window contents Java components paint themselves Anything else: Programmer
When to paint? How to paint?
JButton
Coordinate System
Upside-down Cartesian
(0,0)
(0,height) Ywindow = height - Ycartesian
(width,0)
(width, height)
Painting Components Can paint any component JPanel is good for custom graphics area
JButton
JPanel
Painting in Java import java.awt.Graphics import java.awt.Graphics2D
// Java2
1. Get the “graphics context” of component Graphics g = myJPanel.getGraphics( ); Graphics2D g2 = (Graphics2D) g; 2. Paint in it g2.drawLine(x1,y1, x2,y2);
Graphics Primitives
http://java.sun.com/docs/books/tutorial/2d/geometry/primitives.html
Draw
Point Line
(x,y) (pt1,pt2)
PolyLine (pt list) Arc Oval
(pt, w,h)
Rectangle
(pt, w,h)
RoundRectangle
Polygon
(pt list)
Image
(file, x,y)
Text
(string, x,y)
label
Fill
Graphics Attributes Color Font Stroke attributes: ¾ Line width, dash, end caps, joins, miter Paint attributes: ¾ Color, gradient, texture Composite: ¾ Blending Transforms: ¾ Translate, rotate, flip, shear, scale
Code public class MyPanel extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g); // clears bg Graphics2D g2 = (Graphics2D)g; // our drawing: g2.setColor(new Color(255,0,0)); g2.fillRect(10,10,200,50); g2.setColor(new Color(0,0,0)); g2.drawString("Hello World", 10, 10); } } To paint the inside of a component, override the paintComponent
Hello World
Creating and Drawing to an Image http://java.sun.com/docs/books/tutorial/2d/images/drawonimage.html . . . BufferedImage off_Image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = off_Image.createGraphics();
53
Reading/Loading Image BufferedImage img = null; try { img = ImageIO.read(new File(“mypicture.jpg")); } catch (IOException e) { } boolean Graphics.drawImage(Image img, int x, int y, ImageObserver observer);
54
View more...
Comments