Java course - IAG0040              Java Beans,             Applets & GUIAnton Keks                           2011
Java Beans ●   JavaBeans is a component technology (like CORBA, ActiveX, etc)      –   JavaBeans API allows creation of re...
Bean basics ●   Beans can expose their      –   properties, which can be modified at design time      –   actions (methods...
How to make a Bean? ●   A Java bean is a Java class that      –   follows certain rules (conventions, design patterns), wh...
More features ●     Bean properties can have PropertyEditors assigned ●     More complex editing is possible using the Cus...
Persistence ●     Every bean is Serializable, hence can be easily     serialized/deserialized     –   using ObjectOutputSt...
Warning: Java Beans ≠ EJB ●     EJB are Enterprise Java Beans ●   EJB are part of Java EE (Enterprise Edition) ●   EJB and...
Bean task 1. Write a simple CommentBean       with String property comment 2. Try using the Introspector on it 3. Make it ...
Java GUI toolkits●     Most Java GUI toolkits are cross-platform, as Java itself●     The most popular ones are      –   A...
Java 1.6 desktop additions ●   Cross-platform system tray support      –   SystemTray.getSystemTray();      –   tray.add(n...
Java Applets ●   Applets were the killer-app for Java ●   In short, Applets are GUI Java applications, embedded in HTML   ...
Applet API●    The applet API lets you take advantage of the close relationship     that applets have with Web browsers. S...
Applets and Security ●   The goal is to make browser users feel safe ●   SecurityManager is checking for security violatio...
Deployment of Applets ●   The special <applet> HTML tag is used     –   <applet code=”MyApplet.class” width=”10” height=”1...
Applet task ●   Create CommentApplet ●   Use CommentBean there ●   Use Applet parameters for customization of     backgrou...
JFC ●     JFC = Java Foundation Classes ●     Includes     –   Swing GUI Components     –   Pluggable look-and-feel suppor...
Hello, Swing!●    public class HelloSwing {        private static void createAndShowGUI() {           JFrame frame = new J...
Swing concepts ●     Containers contain other components      –   Top-level (JApplet, JDialog, JFrame), they have contentP...
Swing & Concurrency ●   Most of the API is not thread-safe      –   Thread-safe parts are documented so ●     Swing and AW...
Swing Tips ●     JOptionPane provides various simple dialog boxes      –   showMessageDialog – shows a message box with an...
SWT ●     SWT == Standard Widget Toolkit ●   Fast, portable, native (uses native “themes”) ●     Implemented in Java using...
Hello, SWT! ●   public class HelloSWT {        public static void main (String[] args) {           Display display = new D...
SWT concepts ●     Containers contain other components      –   Top-level container is Shell, which is a Composite      – ...
SWT & Concurrency ●     The Thread that creates the display becomes     the user-interface Thread (aka event-     dispatch...
GUI task ●   Write a simple CalculatorApplication     using either Swing or SWT ●   It must have number buttons from 0 to ...
Upcoming SlideShare
Loading in …5
×

Java Course 14: Beans, Applets, GUI

3,576 views

Published on

Lecture 14 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,576
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
128
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Java Course 14: Beans, Applets, GUI

  1. 1. Java course - IAG0040 Java Beans, Applets & GUIAnton Keks 2011
  2. 2. Java 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)Java course – IAG0040 Lecture 14Anton Keks Slide 2
  3. 3. Bean 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 beanJava course – IAG0040 Lecture 14Anton Keks Slide 3
  4. 4. 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 exceptionsJava course – IAG0040 Lecture 14Anton Keks Slide 4
  5. 5. More 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)Java course – IAG0040 Lecture 14Anton Keks Slide 5
  6. 6. Persistence ● 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 valuesJava course – IAG0040 Lecture 14Anton Keks Slide 6
  7. 7. Warning: Java Beans ≠ EJB ● 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 ● Dont confuse yourselfJava course – IAG0040 Lecture 14Anton Keks Slide 7
  8. 8. Bean 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() method Frame frame = new Frame(); frame.add(new CommentBean()); frame.setSize(w, h); frame.setVisible(true);Java course – IAG0040 Lecture 14Anton Keks Slide 8
  9. 9. Java 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 Java course – IAG0040 Lecture 14 Anton Keks Slide 9
  10. 10. Java 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 checkJava course – IAG0040 Lecture 14Anton Keks Slide 10
  11. 11. Java 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)Java course – IAG0040 Lecture 14Anton Keks Slide 11
  12. 12. Applet 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() Java course – IAG0040 Lecture 14 Anton Keks Slide 12
  13. 13. Applets 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.Java course – IAG0040 Lecture 14Anton Keks Slide 13
  14. 14. Deployment 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 fromJava course – IAG0040 Lecture 14Anton Keks Slide 14
  15. 15. Applet 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 browserJava course – IAG0040 Lecture 14Anton Keks Slide 15
  16. 16. JFC ● 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 toolkitJava course – IAG0040 Lecture 14Anton Keks Slide 16
  17. 17. 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(); } } } } Java course – IAG0040 Lecture 14 Anton Keks Slide 17
  18. 18. Swing 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 mechanismJava course – IAG0040 Lecture 14Anton Keks Slide 18
  19. 19. Swing & 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 thisJava course – IAG0040 Lecture 14Anton Keks Slide 19
  20. 20. Swing 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());Java course – IAG0040 Lecture 14Anton Keks Slide 20
  21. 21. SWT ● 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 manuallyJava course – IAG0040 Lecture 14Anton Keks Slide 21
  22. 22. 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 (); } }Java course – IAG0040 Lecture 14Anton Keks Slide 22
  23. 23. SWT 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 composed Button 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.Java course – IAG0040 Lecture 14Anton Keks Slide 23
  24. 24. SWT & 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 OSs queueJava course – IAG0040 Lecture 14Anton Keks Slide 24
  25. 25. GUI 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: IDEAs Frame Editor can help :-)Java course – IAG0040 Lecture 14Anton Keks Slide 25

×