JFrame and JApplet - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

JFrame and JApplet

Description:

... the different screen resolution/color resolution combinations would be different ... Splash screens. Pop-up menus (now handled by JPopupMenu class) ... – PowerPoint PPT presentation

Number of Views:385
Avg rating:3.0/5.0
Slides: 44
Provided by: webdev5
Category:
Tags: color | japplet | jframe | splash

less

Transcript and Presenter's Notes

Title: JFrame and JApplet


1
JFrame and JApplet
2
Primary or Application Window
  • This is the type of window that appears on a
    screen when an activity or action is started.
  • Required for every function or application.
  • Usually contains some basic controls
  • Frame or Border
  • Title Bar
  • Title Bar Icons
  • Title Bar Text
  • Title Bar Buttons
  • Menu Bar
  • Status Bar
  • Scroll Bar
  • Size Grip

3
More on Primary Windows
  • Should represent an independent function or
    application
  • Use to present constantly used window components
    and controls
  • Menu bar items that are
  • Used frequently
  • Used by most, or all primary and secondary
    windows
  • Controls used by most applications

4
Secondary, Document or Supplemental Windows
  • May contain data actually being processed
  • Typically associated with a single data object,
    and may appear on top of the active window
  • Sizable
  • Movable
  • Scrollable
  • Resemble primary window, but may use the primary
    window menu bar

5
Window sizing
  • Provide large-enough windows to
  • Present all relevant and expected information for
    the task
  • Avoid hiding important information
  • Avoid crowding or visual confusion
  • Minimize the need for scrolling
  • But less than the full size of the entire screen
  • If window is too large, determine
  • Is all the information needed?
  • Is all the information related?
  • Otherwise, make the window as small as possible
  • Optimum window sizes
  • For text, about 12 lines
  • For alphanumeric information, about 7 lines

6
Advantages of different window sizes
  • Larger windows
  • Permit display of more information
  • Facilitate learning data relationships and
    groupings are more obvious
  • Less window manipulation requirements exist
  • Breadth is preferred to depth
  • More efficient data validation and data
    correction can be performed
  • Disadvantages
  • Longer pointer movements are required
  • Windows are more crowded
  • More visual scanning is required
  • Parts are more easily obscured by other windows

7
Multiple Monitors
  • Do NOT assume a single monitor setup
  • Default position for many windows and dialogs is
    in the center of the screen
  • If you ask java what the Screen size is from the
    Toolkit, it reports the total screen size, which
    is the sum of all monitors attached to the system

Monitor 0 1600 x 1200 Origin at 0,0
Monitor 1 1600 x 1200 Origin at 1600,0
Your default positioned dialog in the Center
of the 3200 x 1200 screen
8
Identifying Your Graphics Environment
  • Initial reaction is to use Toolkit.getScreenSize()
  • API says Gets the size of the screen. On
    systems with multiple displays, the primary
    display is used. Multi-screen aware display
    dimensions are available from GraphicsConfiguratio
    n and GraphicsDevice.
  • Oops, on Linux with xinerma extensions (similar
    to windows), a two screen, each at 1600x1200,
    reports a window size of 3200x1200
  • On Windows it is not reliable either
  • Depends on video card configuration
  • Many new cards drive two monitors from a single
    card
  • Even if getScreenSize() did work, it still
    doesnt tell you everything you need to know
  • Use the trusty GraphicsEnvironment class to get
    the information you will need.

9
GraphicsEnvironment class
  • Describes the collection of GraphicsDevice
    objects and Font objects available to a Java
    application on a particular platform.
  • getScreenDevices() returns an array of
    GraphicsDevices for this computer
  • Use the static method getLocalGraphicsEnvironment(
    ) to get a GraphicsEnvironment object for your
    system
  • GraphicsEnvironment ge GraphicsEnvironment.
    getLocalGraphicsEnvironment()

10
GraphicsDevices class
  • Describes the graphics devices that might be
    available in a particular graphics environment.
  • These include screen and printer devices.
  • Use the getScreenDevices() method to pull out the
    screen devices from the GraphicsEnvironment
    object
  • GraphicsDevice gs ge.getScreenDevices()
  • Once you have a graphics device, you need to pull
    off the GraphicsConfiguration object that tells
    you about the current configuration a window is
    using.

11
GraphicsConfiguration class
  • Describes the characteristics of a graphics
    destination such as a printer or monitor.
  • There can be many GraphicsConfiguration objects
    associated with a single graphics device,
    representing different drawing modes or
    capabilities.
  • In a virtual device multi-screen environment in
    which the desktop area could span multiple
    physical screen devices, the bounds of the
    GraphicsConfiguration objects are relative to the
    virtual coordinate system.
  • From the earlier slide, that means the bounds it
    would return are x0,y0,width1600,height1200
    andx1600,y0,width1600,height1200
  • To get a GraphicsConfiguration object
  • Use getDefaultConfiguration() method on a
    GraphicsDevice object
  • Use the getGraphicsConfiguration() method on a
    Window object

12
Managing Monitors
  • There is no nice built in utility to manage
    multiple monitors
  • You need to write a class that build up info for
    you
  • Use that class to create different monitor tags
  • Primary
  • Enumeration
  • Left-of, Right-of
  • NEVER use null as a parent frame for a Dialog
    window, it uses a screen object and not the
    current Configuration.
  • JDialog
  • JOptionPane
  • JFileChooser
  • JColorChooser

13
java.awt.Window
Object
Window
Container
Component
  • Why is it Important?
  • because it is a shared ancestor of the basic
    Swing windows
  • because some good methods that can be accessed by
    JFrame, JWindow etc, are buried here
  • public void addNotify()
  • Makes this Window displayable by creating the
    connection to its native screen resource. This
    method is called internally by the toolkit and
    should not be called directly by programs.
  • public void pack()
  • Causes this Window to be sized to fit the
    preferred size and layouts of its subcomponents.
  • public void toFront() (and toBack())
  • If this Window is visible, brings this Window to
    the front and may make it the focused Window.

14
More on Windows
  • public Toolkit getToolkit()
  • Returns the toolkit of this frame. The toolkit
    gives info on native hardware capabilities.
    Screen size, resolution, sound bell, etc
  • public void setCursor(Cursor cursor)
  • Set the cursor image to a specified cursor.
  • public boolean isActive()
  • Returns whether this Window is active. Only a
    Frame or a Dialog may be active. The native
    windowing system may denote the active Window or
    its children with special decorations, such as a
    highlighted title bar.
  • public boolean isFocused()
  • Returns whether this Window is focused.
  • public boolean isShowing()
  • Checks if this Window is showing on screen.
  • public GraphicsConfiguration getGraphicsConfigurat
    ion()
  • This method returns the GraphicsConfiguration
    used by this Window.
  • public void setLocationRelativeTo(Component c)
  • Sets the location of the window relative to the
    specified component. If the component is not
    currently showing, or c is null, the window is
    centered on the screen. If the bottom of the
    component is offscreen, the window is displayed
    to the right of the component.

15
New in JDK 1.5
  • Includes methods for ensuring a Window, Frame, or
    Dialog is always on top.
  • This feature is not supported on all OSs (Some
    Solaris Window Managers)
  • isAlwaysOnTop()
  • setAlwaysOnTop(boolean)
  • See example Banner.java
  • Set whether a window should appear at the default
    location for the native windowing system the next
    time the Window is made visible
  • setLocationByPlatform(boolean)
  • Position a window and set its size
  • setBounds(int x, int y, int width, int height)

16
JFrame
Object
Window
Container
Component
Frame
JFrame
  • Very similar to AWT Frame (at first glance)
  • One of the few Swing components that do not
    inherit from JComponent. JApplet, JDialog and
    JWindow also are not children of JComponent
  • Internals very different
  • JDK 1.1 you make a frame, set a layout, and add
    your components
  • Frame f new Frame(Foo)
  • f.setLayout(new FlowLayout())
  • f.add(new JButton(Press Me)
  • If you try this in JDK1.2, 1.3 JDK 1.4, you
    would get a java.lang.Error when you run the
    program. JDK 1.5 does not have this limitation
  • JFrame is no longer a simple container , it is
    now a compound structure
  • Allows for more complex, subtle control of window
    contents

17
Anatomy of a JFrame
JFrame
JRootPane
JLayeredPane
Menu Bar (optional)
Content Pane
Glass Pane
18
JFrame Constructors
  • JFrame()
  • Constructs a new Frame that is initially
    invisible.
  • JFrame(String title)
  • Constructs a new, initially invisible Frame with
    the specified title.
  • JFrame(GraphicsConfiguration gc)
  • Constructs a new, initially invisible Frame on
    the specified configuration.
  • JFrame(String title, GraphicsConfiguration gc)
  • Constructs a new, initially invisible Frame with
    the specified title on the specified
    configuration.
  • The GraphicsConfiguration class describes the
    characteristics of a graphics destination such as
    a printer or monitor. There can be many
    GraphicsConfiguration objects associated with a
    single graphics device. For example, on X11
    windowing systems, each visual is a different
    GraphicsConfiguration. On PCs and Macintoshes,
    the different screen resolution/color resolution
    combinations would be different
    GraphicsConfiguration objects.

19
Multiple Graphics Devices
  • To get the graphics devices, use the
    GraphicsEnvironment's getScreenDevices() method.
  • You can get the default configuration for each
    device with the getDefaultConfiguration() method.
  • Code Example MultipleJFrames.java
  • GraphicsEnvironment ge GraphicsEnvironment.getLo
    calGraphicsEnvironment()
  • GraphicsDevice gs ge.getScreenDevices()
  • for (int j 0 j lt gs.length j)
  • System.out.println("Checking Device " j)
  • GraphicsDevice gd gsj
  • GraphicsConfiguration gc
    gd.getConfigurations()
  • System.out.println(" DefaultConfiguration
    for Device" j
  • " has bounds of "
  • gd.getDefaultConfiguration().getBounds()
  • "\n and color model of "
  • gd.getDefaultConfiguration().getColorMode
    l())

20
Coordinates of Multiple Graphics Devices
  • From the Java API
  • In a virtual device multi-screen environment in
    which the desktop area could span multiple
    physical screen devices, the bounds of the
    GraphicsConfiguration objects are relative to the
    virtual coordinate system. When setting the
    location of a component, use getBounds to get the
    bounds of the desired GraphicsConfiguration and
    offset the location with the coordinates of the
    GraphicsConfiguration, as the following code
    sample illustrates
  • Frame f new Frame(GraphicsConfiguration gc)
  • Rectangle bounds gc.getBounds()
  • f.setLocation(10 bounds.x, 10 bounds.y)

21
JFrame Methods
  • public void setDefaultCloseOperation(int
    operation)
  • DO_NOTHING_ON_CLOSE - do not do anything -
    require the program to handle the operation in
    the windowClosing method of a registered
    WindowListener object. This is useful for
    "catching" closing events and preventing them
    from occuring until a condition is met.
  • HIDE_ON_CLOSE - automatically hide the frame
    after invoking any registered WindowListener
    object. This is the default operation.
  • DISPOSE_ON_CLOSE - automatically hide and dispose
    the frame after invoking any registered
    WindowListener objects
  • EXIT_ON_CLOSE - Exit the application by way of
    System.exit. Only use this in applications.

22
More JFrame Methods
  • public void update(Graphics g)
  • public JMenuBar getJMenuBar()
  • public void setJMenuBar(JMenuBar menubar)
  • protected void setRootPaneCheckingEnabled(boolean
    flag)
  • get/set pairs for RootPane, LayeredPane,
    ContentPane and GlassPane
  • public void pack()
  • public void show()
  • public void setResizeable(boolean b)
  • public invalidate()
  • public validate()
  • public revalidate()
  • similar to repaint() calls

23
Adding components to a JFrame
  • In JDK 1.5
  • JFrame f new JFrame(Foo)
  • f.add(new JButton(Press Me))
  • or in earlier versions
  • JFrame f new JFrame(Foo)
  • Container cp f.getContentPane()
  • cp.add(new JButton(Press Me))
  • or
  • f.getContentPane().add(new JButton(Press Me))

24
Thread Issues and JFrames
  • In December 2003, Sun issued a tutorial stating
    that the following sequence should not be used
    when creating a Jframe
  • pack()
  • setVisible(true)
  • The pack() or setVisible() methods create the
    associated helper for the frame, and the system
    creates the event dispatch thread.
  • The Thread may then call listeners while pack and
    validate() are still processing.
  • May generate some event problems in more complex
    GUIs
  • Recommended method is as follows
  • final JFrame jf new JFrame()
  • Runnable showFrame new Runnable()
  • public void run()
  • jf.pack()
  • jf.setVisible(true)
  • SwingUtilities.invokeLater(showFrame)

25
Code Example, SimpleJFrame.java and
SimpleJFrame2.java
26
Controlling the LF of the JFrame
  • Undecorated JFrames
  • You can make undecorated (no window borders)
    JFrames by doing the following
  • JFrame jf new JFrame()
  • jf.setUndecorated(true)
  • Dont abuse this feature!
  • Look and Feel Decorated JFrames
  • You can let the Look and Feel decorate the
    decorate the JFrame by doing the following
  • JFrame jf new JFrame()
  • jf.setUndecorated(true)
  • jf.getRootPane().setWindowDecorationStyle(JRootPan
    e.FRAME)

27
Controlling Size/Location of JFrames
  • Setting Size
  • setSize(Dimension d)
  • setBounds(int x, int y, int width, int height)
    JDK 1.5
  • setResizable(boolean flag)
  • pack()
  • Setting Location
  • setLocation(int x, int y)
  • setLocation(Point p)
  • setLocationByPlatform(boolean flag) JDK 1.5
  • see next slide for example
  • setLocationRelativeTo(Component c)
  • setBounds(int x, int y, int width, int height)

28
PlatformLocation.java
29
State of JFrame on the Desktop
  • You can control the state of the JFrame (or
    Frame) on the Desktop with
  • setExtendedState(int state)
  • This sets the state of this frame. The state is
    represented as a bitwise mask.
  • NORMAL indicates that no state bits are set.
  • ICONIFIED Iconifies the JFrame
  • MAXIMIZED_HORIZ Maximize the JFrame Horizontally
  • MAXIMIZED_VERT Maximize the JFrame Vertically
  • MAXIMIZED_BOTH Concatenates MAXIMIZED_HORIZ and
    MAXIMIZED_VERT.
  • Note that if the state is not supported on a
    given platform, nothing will happen. The
    application may determine if a specific state is
    available via the java.awt.ToolkitisFrameStateSup
    ported(int state) method.
  • In JDKs before JDK 1.4, there is a setState()
    method which is a subset of the above methods

30
JWindow
Object
Window
Container
Component
JWindow
  • Borderless window, very similar to an
    undecorated JFrame
  • User has no interaction with the window edges
  • Splash screens
  • Pop-up menus (now handled by JPopupMenu class)
  • If no parent given with constructor, window
    cannot get focus
  • JWindow()
  • JWindow(JFrame frame)
  • JWindow (Window window)
  • JWindow(GraphicsConfiguration gc)
  • JWindow(Window window, GraphicsConfiguration gc)
  • Use for informational purposes only, be careful
    on placement, since the user can't move them!

31
JApplet
Object
Panel
Container
Component
Applet
JApplet
  • Swing equivalent of the AWT Applet class
  • An extended version of java.applet.Applet that
    adds support for interposing input and painting
    behaviour in front of the applets children (see
    glassPane), support for special children that are
    managed by a LayeredPane (see rootPane) and for
    Swing MenuBars.
  • Internal structure similar to JFrame (JRootPane,
    JContentPane)
  • You can now use JMenuBar in an applet, unlike in
    JDK 1.1
  • Default layout manager is BorderLayout

32
JApplet methods
  • Constructors
  • public JApplet()
  • Methods
  • public void setDefaultCloseOperation(int
    operation)
  • public void update(Graphics g)
  • public JMenuBar getJMenuBar()
  • public void setJMenuBar(JMenuBar menubar)
  • protected void setRootPaneCheckingEnabled(boolean
    flag)
  • get/set pairs for RootPane, LayeredPane,
    ContentPane and GlassPane
  • public void pack()
  • public void show()
  • To disable the Warning Java Applet Window
    message
  • getRootPane().putClientProperty(defeatSystemEvent
    QueueCheck, Boolean.TRUE)

33
Glass Panes
  • Fills the entire pane
  • Instance of JPanel
  • Non-opaque
  • Since mouse events are normally processed by the
    top-most visible component
  • Glass pane usually doesnt handle mouse input
  • If it does, it will block it from the rest of the
    window
  • Windows below are not disabled, they just dont
    get events
  • You can use the glass pane to
  • Make a status bar over an initial window, showing
    initiation progress. The bar can be in the glass
    pane, and if you handle mouse events, the app
    beneath it will not get anything yet

34
JLayeredPane
  • Manages its components in layers

JLayeredPane constants and their relative
positions
35
Panels
JComponent
JPanel
  • Swing equivalent of Panel is JPanel
  • JPanel is your general purpose container/canvas
  • Constructors
  • JPanel()
  • JPanel(boolean isDoubleBuffered)
  • JPanel(LayoutManager layout)
  • JPanel(LayoutManager layout, boolean
    isDoubleBuffered)
  • Often used as containers for other layouts
  • JPanels inherit from JComponent, so we can use
    borders
  • JPanel default layout is FlowLayout
  • No significant methods, only four methods for the
    class dealing with getting and updating UI,
    accessibility, paramString

36
Applet/Application combinations
  • A quick way to implement a file as both an
    application and an applet is as follows
  • Step one let your top level window inherit from
    JApplet
  • Step two attach a main method, which in turn
    creates a JFrame which shares the content pane of
    the applet
  • public class Test extends JApplet
  • public void init()
  • public static void main(String argv)
  • final JFrame f new JFrame()
  • JApplet applet new Test()
  • applet.init()
  • f.setContentPane(applet.getContentPane())

37
Case Studies
38
Case Studies
39
Case Studies
  • Remembers Last Size
  • Note hidden border that shows up during screen
    capture
  • App doesn't want to use OS window style

40
How does a JFrame remember its size?
  • In the last example, we saw that many
    applications remember their last size and
    location on the screen.
  • How can we do this in Java?
  • java.util.prefs.Preferences to the rescue!
  • java.util.prefs.Preferences appeared in Java
    1.4.1 as way to store configuration data for
    applications and individual users.

41
Preferences
  • Stores a hashtable of preferences on the native
    OS
  • Windows in Registry
  • Unix/Linux
  • /etc/.java for system preferences
  • /.java for user preferences
  • Unlike property files, you don't have to manage
    the location of the Preferences, the JVM does it
    for you.
  • Allows application wide preferences (system) and
    user specific (user)
  • Mechanism provides for defaults when asking for a
    value that isn't there
  • Preferences are package based, not class based.
    The class you provide is a map to the package
    used.

42
How to use Preferences
  • // get object for storing preferences for MyClass
  • Preferences up Preferences.userNodeForPackage (
    MyClass.class )
  • ...
  • // store preferences, keyvalue
  • userPrefs.putInt( "width", width )
  • userPrefs.putInt( "height", height )
  • ...
  • // fetch preferences, key,default
  • int width userPrefs.getInt( "width", 100 )
  • int height userPrefs.getInt( "height", 200 )
  • ...
  • // write any changes in Preferences out to
    backing store
  • userPrefs.flush()

43
Intelligent JFrame
  • MemoryFrame.java is an example of a JFrame using
    Preferences to remember its last size and location
Write a Comment
User Comments (0)
About PowerShow.com