java course 14: beans, applets, gui
DESCRIPTION
Lecture 14 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-courseTRANSCRIPT
Java Beans,Java Beans,Applets & GUIApplets & GUI
Java course - IAG0040Java course - IAG0040
Anton Keks 2011
Lecture 14Lecture 14Slide Slide 22
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Java BeansJava Beans
● JavaBeans is a component technology (like CORBA, ActiveX, etc)
– JavaBeans API allows creation of reusable, self-contained, cross-platform components.
– Java components are called “beans”
– Beans can be used in Applets, applications, or other Beans.
– Beans are usually UI components, but it is not a requirement● There are many JavaBeans-compatible visual tools
● Formerly, there was the BDK (Bean Development Kit), which contained BeanBox. Now it is superseded by BeanBuilder.
● Nowadays, the concept of “beans” is used also outside of JavaBeans (not using java.beans API), e.g. in many server-side frameworks. Sometimes these beans are called POJOs (Plain Old Java Objects)
Lecture 14Lecture 14Slide Slide 33
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Bean basicsBean basics● Beans can expose their
– properties, which can be modified at design time
– actions (methods to do something)
– events● java.beans.Introspector analyses Java Bean classes
– Generally automatically using Reflection API
– Or using the provided BeanInfo implementation (optional)● it must be named XyzBeanInfo for bean named Xyz
● Introspector.getBeanInfo(Xyz.class) will return a BeanInfo instance, describing the Xyz bean
Lecture 14Lecture 14Slide Slide 44
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
How to make a Bean?How to make a Bean?
● A Java bean is a Java class that
– follows certain rules (conventions, design patterns), which enable dynamic discovery of its features
– is Serializable (not strictly enforced)
– has a default constructor (parameter-less)
– can extend any class (no restrictions), but usually they extend some GUI container classes
– has properties defined by corresponding getters and setters (getXxx(), isXxx() and setXxx() public methods, where xxx is the property name)
– has public void action methods
● methods can throw any exceptions
Lecture 14Lecture 14Slide Slide 55
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
More featuresMore features
● Bean properties can have PropertyEditors assigned
● More complex editing is possible using the Customizer interface (it can customize the whole bean at once)
● Aside from properties, Beans can have events
– event listeners must implement an interface (e.g. ActionListener)
– Bean must provide two methods: addXXX() and removeXXX()● addActionListener(ActionListener listener)● removeActionListener(ActionListener listener)
– The interface must define a method, taking the event object● actionPerformed(ActionEvent e)
Lecture 14Lecture 14Slide Slide 66
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
PersistencePersistence
● Every bean is Serializable, hence can be easily serialized/deserialized– using ObjectOutputStream and ObjectInputStream
● Long-term bean-specific serialization to XML is also possible– using XMLEncoder and XMLDecoder– these enforce Java bean convention very strictly– smart enough to persist only required (restorable)
properties, i.e. read-write properties with non-default values
Lecture 14Lecture 14Slide Slide 77
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Warning: Java Beans Warning: Java Beans ≠≠ EJBEJB
● EJB are Enterprise Java Beans● EJB are part of Java EE (Enterprise Edition)● EJB and JavaBeans have very few in common● EJB = bad thing (heavy-weight)
– at least before EJB 3.0– even EJB architects at Sun agree on that now
● Don't confuse yourself
Lecture 14Lecture 14Slide Slide 88
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Bean taskBean task
1. Write a simple CommentBean with String property comment
2. Try using the Introspector on it
3. Make it a GUI bean by extending java.awt.Canvas
4. Make it display text: override the paint() method, use g.drawString()
5. Make the comment text scroll from right to left by using a Timer or a manually written Thread
6. Tip: run it temporarily with this code in the main() methodFrame frame = new Frame(); frame.add(new CommentBean());frame.setSize(w, h); frame.setVisible(true);
Lecture 14Lecture 14Slide Slide 99
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Java GUI toolkitsJava GUI toolkits
● Most Java GUI toolkits are cross-platform, as Java itself
● The most popular ones are
– AWT (Abstract Widgets Toolkit), java.awt – the first GUI toolkit for Java, the most basic one, sometimes may look ugly.
● The principle of LCD (least common denominator)– JFC Swing, javax.swing – pure Java, supports pluggable look-and-
feels, more widgets, more powerful.
● Included in JRE distribution– SWT (Standard Widget Toolkit), org.eclipse.swt – developed for
Eclipse, can be used stand-alone.
● Provides native look-and-feel on every platform.● Implemented as thin layer on native libraries for many platforms
Lecture 14Lecture 14Slide Slide 1010
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Java 1.6 desktop additionsJava 1.6 desktop additions● Cross-platform system tray support
– SystemTray.getSystemTray();
– tray.add(new TrayIcon(img, “Hello”));
● Cross-platform java.awt.Desktop API
– Desktop.getDesktop();
– desktop.browse() - opens a web browser
– desktop.mail() - opens a mail client
– open(), edit(), print() - for arbitrary documents
– all this uses file/URL associations in the OS● These may not be supported on each platform
– use isSupported() methods to check
Lecture 14Lecture 14Slide Slide 1111
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Java AppletsJava Applets● Applets were the killer-app for Java
● In short, Applets are GUI Java applications, embedded in HTML pages, and distributed over the Internet
● Convenient to deploy centrally, convenient to run
● Built-in security
● Nowadays not as popular, because of Servlets, AJAX, Flash, and aggressiveness of Microsoft (Java is no longer shipped with Windows by default)
● Applets are created by extending one of these classes:
– java.applet.Applet – older, AWT-based API
– javax.swing.JApplet – newer, Swing-based API (extends Applet itself)
Lecture 14Lecture 14Slide Slide 1212
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Applet APIApplet API● The applet API lets you take advantage of the close relationship
that applets have with Web browsers. See both Applet and AppletContext (obtainable with getAppletContext())
● Applets can use these APIs to do the following:
– Be notified by the browser of state changes: start(), stop(), destroy()
– Load data files specified relative to the URL of the applet or the page in which it is running: getCodeBase(), getDocumentBase(), getImage()
– Display short status strings: showStatus()
– Make the browser display a document: showDocument()
– Find other applets running in the same page: getApplets()
– Play sounds: getAudioClip(), play()
– Get parameters specified by the user in the <APPLET> tag: getParameter(), getParameterInfo()
Lecture 14Lecture 14Slide Slide 1313
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Applets and SecurityApplets and Security● The goal is to make browser users feel safe
● SecurityManager is checking for security violations
● SecurityException (unchecked) is thrown if something is not allowed
● In general, the following is forbidden:
– no reading/writing files on local host
– network connections only to the originating host
– no starting of programs, no loading of libraries
– all separate applet windows are identified with a warning message
– some system properties are hidden
● Trusted Applets can be allowed to do otherwise forbidden things
– They are digitally signed applets, which can ask user if he/she allows to do something. See the keytool program in JDK.
Lecture 14Lecture 14Slide Slide 1414
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Deployment of AppletsDeployment of Applets
● The special <applet> HTML tag is used
– <applet code=”MyApplet.class” width=”10” height=”10”><param name=”myparam” value=”avalue”/>
</applet>
– Additional attributes:
● codebase – defines either relative of absolute URL where class files are located
● archive – can specify jar file(s), where to load classes and other files from
Lecture 14Lecture 14Slide Slide 1515
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Applet taskApplet task
● Create CommentApplet
● Use CommentBean there
● Use Applet parameters for customization of background color and comment
● Create an text field and use it for changing the comment String at runtime
● Display the java-logo.gif within the Applet by using getImage(getCodeBase(), “filename”) and g.drawImage(img, 0, 0, this)
● Deploy applet and view using a web browser
Lecture 14Lecture 14Slide Slide 1616
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
JFCJFC
● JFC = Java Foundation Classes● Includes
– Swing GUI Components– Pluggable look-and-feel support– Accessibility API– Java2D API– Drag-and-drop support– Internationalization
● JFC/Swing currently is the most popular GUI toolkit
Lecture 14Lecture 14Slide Slide 1717
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Hello, Swing!Hello, Swing!
● public class HelloSwing {private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JLabel label = new JLabel("Hello, Swing!");frame.add(label);frame.pack();frame.setVisible(true);
}public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
createAndShowGUI();}
}} }
Lecture 14Lecture 14Slide Slide 1818
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Swing conceptsSwing concepts
● Containers contain other components
– Top-level (JApplet, JDialog, JFrame), they have contentPane (e.g. JPanel) and optional JMenuBar
– General-purpose (JPanel, JScrollPane, JSplitPane, JTabbedPane, JToolBar, etc)
– containers provide add() methods
● Layouts control positions of child components
● Most noncontainer components have optional Model interfaces (e.g. ButtonModel), which can store their state (think of MVC pattern)
● The overall design follows JavaBeans conventions, including the event handling mechanism
Lecture 14Lecture 14Slide Slide 1919
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Swing & ConcurrencySwing & Concurrency
● Most of the API is not thread-safe
– Thread-safe parts are documented so● Swing and AWT use their own event dispatch thread
– most interactions with GUI components should happen there
– SwingUtilities class provides invokeLater() and invokeAndWait()
– event handling code must be as short as possible● Longer running code must be in separate threads
– this allows GUI to always stay responsive, avoids freezing
– Java 1.6 introduced SwingWorker to simplify this
Lecture 14Lecture 14Slide Slide 2020
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Swing TipsSwing Tips
● JOptionPane provides various simple dialog boxes
– showMessageDialog – shows a message box with an OK button
– showConfirmDialog – shows a confirmation dialog with Yes, No, Cancel, etc buttons
– showInputDialog – shows a dialog for entering text
● Look-and-feel is controlled by the UIManager
– UIManager.setLookAndFeel(“com.sun.java.swing.plaf.”+ “motif.MotifLookAndFeel");
– UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
– UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
Lecture 14Lecture 14Slide Slide 2121
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
SWTSWT
● SWT == Standard Widget Toolkit
● Fast, portable, native (uses native “themes”)
● Implemented in Java using native Java adapters
● API is a bit less flexible than Swing, not 100% JavaBean-compatible
● UI access is strictly single-threaded
● Not included in standard distribution, must be deployed manually
Lecture 14Lecture 14Slide Slide 2222
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Hello, SWT!Hello, SWT!
● public class HelloSWT {public static void main (String[] args) {
Display display = new Display();Shell shell = new Shell(display);Label label = new Label(shell, SWT.BORDER);label.setText(“Hello, SWT!”);shell.pack();shell.open();while (!shell.isDisposed()) {
if (!display.readAndDispatch())display.sleep();
} display.dispose ();
}}
Lecture 14Lecture 14Slide Slide 2323
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
SWT conceptsSWT concepts● Containers contain other components
– Top-level container is Shell, which is a Composite
– Widget constructors take parent Composite as a parameter. No relocations or multiple parents.
– All widgets take style bits in constructors, which can be composedButton btn = new Button(shell, SWT.PUSH | SWT.BORDER);
● Display class provides the environment
● Layouts control positions of child components, each control can have its LayoutData assigned
● Not all API conforms to the JavaBeans conventions; event handling mechanism is pretty standard
● All widgets must be manually dispose()d! Parent disposes its children.
Lecture 14Lecture 14Slide Slide 2424
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
SWT & ConcurrencySWT & Concurrency
● The Thread that creates the display becomes the user-interface Thread (aka event-dispatching thread)– other threads cannot access UI components
– Display provides methods to ease this task● asyncExec, syncExec, timerExec – they all execute
provided Runnable implementation in the UI thread
● Event loop must be executed manually– Display.readAndDispatch() in a loop
● processes events on native OS's queue
Lecture 14Lecture 14Slide Slide 2525
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
GUI taskGUI task
● Write a simple CalculatorApplication using either Swing or SWT
● It must have number buttons from 0 to 9, +, -, *, /, =, and Clear. Label must be used for displaying the current number or the result.
● Note: IDEA's Frame Editor can help :-)