SlideShare a Scribd company logo
Java course - IAG0040




              Java Beans,
             Applets & GUI


Anton Keks                           2011
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 14
Anton Keks                                                             Slide 2
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 bean

Java course – IAG0040                                        Lecture 14
Anton Keks                                                       Slide 3
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

Java course – IAG0040                                              Lecture 14
Anton Keks                                                             Slide 4
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 14
Anton Keks                                                           Slide 5
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 values
Java course – IAG0040                                Lecture 14
Anton Keks                                               Slide 6
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
 ●
     Don't confuse yourself


Java course – IAG0040                               Lecture 14
Anton Keks                                              Slide 7
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 14
Anton Keks                                                        Slide 8
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
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 check
Java course – IAG0040                                         Lecture 14
Anton Keks                                                      Slide 10
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 14
Anton Keks                                                               Slide 11
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
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 14
Anton Keks                                                                 Slide 13
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 from




Java course – IAG0040                                                     Lecture 14
Anton Keks                                                                  Slide 14
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 browser
Java course – IAG0040                                   Lecture 14
Anton Keks                                                Slide 15
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 toolkit
Java course – IAG0040                               Lecture 14
Anton Keks                                            Slide 16
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
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 mechanism


Java course – IAG0040                                           Lecture 14
Anton Keks                                                        Slide 18
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 this
Java course – IAG0040                                          Lecture 14
Anton Keks                                                       Slide 19
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 14
Anton Keks                                                       Slide 20
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 manually




Java course – IAG0040                                         Lecture 14
Anton Keks                                                      Slide 21
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 14
Anton Keks                                                 Slide 22
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 14
Anton Keks                                                               Slide 23
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 OS's queue
Java course – IAG0040                                    Lecture 14
Anton Keks                                                 Slide 24
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: IDEA's Frame Editor can help :-)




Java course – IAG0040                           Lecture 14
Anton Keks                                        Slide 25

More Related Content

What's hot

Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
Sagar Verma
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
Ayushman Jain
 
Core Java
Core JavaCore Java
Core Java
Prakash Dimmita
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring tools
Sathish Chittibabu
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Core java1
Core java1Core java1
Core java1
Ravi varma
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
Java features
Java featuresJava features
Java features
Prashant Gajendra
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
Jorge Hidalgo
 
Core java
Core java Core java
Core java
Ravi varma
 

What's hot (18)

Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
Core Java
Core JavaCore Java
Core Java
 
JDT Fundamentals 2010
JDT Fundamentals 2010JDT Fundamentals 2010
JDT Fundamentals 2010
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring tools
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Core java1
Core java1Core java1
Core java1
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java features
Java featuresJava features
Java features
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Core java
Core java Core java
Core java
 

Viewers also liked

Java beans
Java beansJava beans
Java beans
Bipin Bedi
 
Java beans
Java beansJava beans
Java beans
Mukesh Tekwani
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
shravan kumar upadhayay
 
Code Division Multiple Access- CDMA
Code Division Multiple Access- CDMA Code Division Multiple Access- CDMA
Code Division Multiple Access- CDMA
ViVek Patel
 
Introduction to java beans
Introduction to java beansIntroduction to java beans
Introduction to java beans
Hitesh Parmar
 
IS-95 Cdma
IS-95 CdmaIS-95 Cdma
IS-95 Cdma
yogesh singh
 

Viewers also liked (12)

Javabeans
JavabeansJavabeans
Javabeans
 
Java beans
Java beansJava beans
Java beans
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 
Java beans
Java beansJava beans
Java beans
 
javabeans
javabeansjavabeans
javabeans
 
Java Beans
Java BeansJava Beans
Java Beans
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
Java beans
Java beansJava beans
Java beans
 
Java beans
Java beansJava beans
Java beans
 
Code Division Multiple Access- CDMA
Code Division Multiple Access- CDMA Code Division Multiple Access- CDMA
Code Division Multiple Access- CDMA
 
Introduction to java beans
Introduction to java beansIntroduction to java beans
Introduction to java beans
 
IS-95 Cdma
IS-95 CdmaIS-95 Cdma
IS-95 Cdma
 

Similar to Java Course 14: Beans, Applets, GUI

Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
dhananajay95
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel Fomitescu
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
Arun Gupta
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
divaskrgupta007
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
Home
 
Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)
smancke
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
Murugesh33
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
Murugesh33
 
java slides
java slidesjava slides
java slides
RizwanTariq18
 
Java
JavaJava
Java
kavirishi
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
Leaner microservices with Java 10
Leaner microservices with Java 10Leaner microservices with Java 10
Leaner microservices with Java 10
Arto Santala
 
Applet Returns: The new generation of Java Plug-ins
Applet Returns: The new generation of Java Plug-insApplet Returns: The new generation of Java Plug-ins
Applet Returns: The new generation of Java Plug-ins
Serge Rehem
 
Migrating to Java 11
Migrating to Java 11Migrating to Java 11
Migrating to Java 11
Arto Santala
 
Java review00
Java review00Java review00
Java review00saryu2011
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
OmegaHub
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
Shaharyar khan
 

Similar to Java Course 14: Beans, Applets, GUI (20)

Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
java slides
java slidesjava slides
java slides
 
Java
JavaJava
Java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Leaner microservices with Java 10
Leaner microservices with Java 10Leaner microservices with Java 10
Leaner microservices with Java 10
 
Applet Returns: The new generation of Java Plug-ins
Applet Returns: The new generation of Java Plug-insApplet Returns: The new generation of Java Plug-ins
Applet Returns: The new generation of Java Plug-ins
 
Migrating to Java 11
Migrating to Java 11Migrating to Java 11
Migrating to Java 11
 
Java review00
Java review00Java review00
Java review00
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
Anton Keks
 

More from Anton Keks (13)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 

Java Course 14: Beans, Applets, GUI

  • 1. Java course - IAG0040 Java Beans, Applets & GUI Anton Keks 2011
  • 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 14 Anton Keks Slide 2
  • 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 bean Java course – IAG0040 Lecture 14 Anton Keks Slide 3
  • 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 exceptions Java course – IAG0040 Lecture 14 Anton Keks Slide 4
  • 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 14 Anton Keks Slide 5
  • 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 values Java course – IAG0040 Lecture 14 Anton Keks Slide 6
  • 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 ● Don't confuse yourself Java course – IAG0040 Lecture 14 Anton Keks Slide 7
  • 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 14 Anton Keks Slide 8
  • 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. 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 check Java course – IAG0040 Lecture 14 Anton Keks Slide 10
  • 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 14 Anton Keks Slide 11
  • 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. 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 14 Anton Keks Slide 13
  • 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 from Java course – IAG0040 Lecture 14 Anton Keks Slide 14
  • 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 browser Java course – IAG0040 Lecture 14 Anton Keks Slide 15
  • 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 toolkit Java course – IAG0040 Lecture 14 Anton Keks Slide 16
  • 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. 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 mechanism Java course – IAG0040 Lecture 14 Anton Keks Slide 18
  • 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 this Java course – IAG0040 Lecture 14 Anton Keks Slide 19
  • 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 14 Anton Keks Slide 20
  • 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 manually Java course – IAG0040 Lecture 14 Anton Keks Slide 21
  • 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 14 Anton Keks Slide 22
  • 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 14 Anton Keks Slide 23
  • 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 OS's queue Java course – IAG0040 Lecture 14 Anton Keks Slide 24
  • 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: IDEA's Frame Editor can help :-) Java course – IAG0040 Lecture 14 Anton Keks Slide 25