SlideShare a Scribd company logo
1 of 25
Download to read offline
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 AgileAnton 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 introductionSagar Verma
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragonAyushman Jain
 
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 toolsSathish 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
 
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 javaAjay Sharma
 
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
 

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 (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 prasentationdhananajay95
 
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/JDBCFAKHRUN NISHA
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro 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 2010Arun Gupta
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginersdivaskrgupta007
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)smancke
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxMurugesh33
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxMurugesh33
 
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 10Arto 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-insSerge Rehem
 
Migrating to Java 11
Migrating to Java 11Migrating to Java 11
Migrating to Java 11Arto Santala
 
Java review00
Java review00Java review00
Java review00saryu2011
 
OOP with Java
OOP with JavaOOP with Java
OOP with JavaOmegaHub
 
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)
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_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 testerAnton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton 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 StreamsAnton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsAnton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton 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 engineerAnton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software DeveloperAnton 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

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

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