Predavanje br. index|1|2|3|4|5|6|7|8|9|10|11|12|13|14|HOME


Èetrnaesto predavanje – Swing

Uvod u Swing – Japplet – Jframe – Look and Feel – Jlabel – Jbutton – Jpanel – Jslider – JcolorChooser – interni frameovi – JoptionPane – Jtoolbar – JeditorPane – JcheckBox – JradioButton – JfileChooser – JtextField – JtextArea – Jlist – Jtree - ispis


Introductory Material

·         Introduction & and Extended Table of Contents (This page)

·         Swing Overview

o        Main New Features

o        Swing Availability

o        Getting More Info

o        Main Differences in Use

o        Mixing AWT and Swing Components (don't!)

 

Uvod u Swing

1. Main New Features

2. Swing is Standard in Java 2 (aka Java 1.2)

3. Separate Swing package can be added to Java 1.1.

4. Getting More Info.

See the on-line Java 2 API or the books in the Swing/JFC section of http://www.apl.jhu.edu/~hall/java/Java-Books.html.

5. Components are named JXxx.

E.g. JFrame, JPanel, JApplet, JDialog, JButton, etc.

6. There is an almost-equivalent Swing component for most AWT components.

7. Do drawing in paintComponent, not paint.

8. Instead of adding components directly to frames or applets, use the content pane

9. Model-View-Controller architecture lets you change the internal data representation for lists, trees, tables, etc.

10. Swing was in the com.sun.java.swing package in beta releases of 1.2. Switched to javax.swing in 1.2 final.

11. Default "look and feel" is a Java-specific one.

12. Mixing AWT and Swing is doomed.

AWT components are always on top, and z-ordering problems catch you in many unexpected ways. Stick with the AWT or move completely to Swing.


 

 

Using Top-Level Containers

·         JApplet

o        General Info

o        Differences from Applet

o        Example

JApplet

1. No browser yet supports Java 1.2.

2. Most usage is the same as with Applet

3. Main differences in use

4. JApplet Example: Source Code

This simple example shows the steps required to get what you would have in the AWT if you had a simple applet whose init method did nothing but drop three buttons into the window.

JAppletExample.java (Download source code)

 
import java.awt.*;
import javax.swing.*;
 
/** Tiny example showing the main differences in using 
 *  JApplet instead of Applet: using the content pane,
 *  getting Java (Metal) look and feel by default, and
 *  having BorderLayout be the default instead of FlowLayout.
 *  1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */
 
public class JAppletExample extends JApplet {
  public void init() {
    WindowUtilities.setNativeLookAndFeel();
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
  }
}
 
 
 
 
 
 
 
import java.awt.*;
import javax.swing.*;
 
public class JAppletExample extends JApplet {
  public void init() {
    WindowUtilities.setNativeLookAndFeel();
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
  }
}

Note: the setNativeLookAndFeel code is presented in WindowUtilities.java.

 

--------------------------------------------------------------------------- WindowUtilities.java

import javax.swing.*;
import java.awt.*;
 
/** A few utilities that simplify using windows in Swing.
 *  1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */
 
public class WindowUtilities {
 
  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */
 
  public static void setNativeLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }
 
  public static void setJavaLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }
 
   public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }
 
  /** A simplified way to see a JPanel or other Container.
   *  Pops up a JFrame with specified Container as the content pane.
   */
 
  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }
 
  /** Uses Color.white as the background color. */
 
  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height, title, Color.white));
  }
 
  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */
 
  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
}

 

 

 


·         JFrame

o        General Info

o        Differences from Frame

o        Example

 

1. As in the AWT, starting point for graphical applications.

2. One of few Swing components that is built on an underlying "heavyweight" window.

3. Main differences in use compared to Frame:

4. JFrame Example: Source Code

This shows the steps required to imitate what you would get in the AWT if you popped up a simple Frame, set the layout manager to FlowLayout, and dropped three buttons into it.

JFrameExample.java (Download source code)

 
import java.awt.*;
import javax.swing.*;
 
public class JFrameExample {
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    JFrame f = new JFrame("This is a test");
    f.setSize(400, 150);
    Container content = f.getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
    f.addWindowListener(new ExitListener());
    f.setVisible(true);
  }
}

Note: also requires WindowUtilities.java, shown earlier.

ExitListener.java (Download source code)

 
import java.awt.*;
import java.awt.event.*;
 
/** A listener that you attach to the top-level Frame or JFrame of
 *  your application, so quitting the frame exits the application.
 *  1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */
 
public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}
 
 
 
 
 
 
 
import java.awt.*;
import java.awt.event.*;
 
public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}

 


 

·         Look & Feel

o        LAF Availability

o        Specifying Native LAF

o        Examples

1. Default is "Java LAF" (or "Metal"), a custom look and feel similar to the Windows look.

2. Motif look available on all platforms. Windows and Mac looks are only available on their native platforms.

3. You can change look at runtime.

4. You can get AWT behavior of using native look.

5. Changing the Look and Feel: Examples

Here are some utility functions that set the LAF to native, Java (Metal), and Motif, respectively. Since I think that most users will expect the native LAF, I almost always call setNativeLookAndFeel at the beginning of Swing programs.

WindowUtilities.java (Download source code)

import javax.swing.*;
import java.awt.*;
 
public class WindowUtilities {
  public static void setNativeLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }
 
  public static void setJavaLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }
 
   public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }
 
  ...
 
}

6. Example: Windows LAF (Sun SwingSet Demo)

 


Simple Swing Components

·         JLabel

o        Basics

o        New Features: Images, Borders, and HTML Content

o        Example

 

1. JLabel Basics

In many cases, JLabel is used exactly like Label: as a way to display text. However, since a JLabel can have an image instead of or in addition to the text, it is also frequently used as a way to put an image in a display.

2. New Features: Images, Borders, and HTML Content

A JLabel has three major features that Label does not.

The first is the ability to display images, usually by supplying an ImageIcon eiher to the constructor or via a call to setIcon. The use of icons in JLabel is just like the use in JButton, so see the Swing Tutorial JButton section for more details and code examples. For a quick preview, however, see the third JLabel in the example below.

The second new feature is the ability to place borders around the labels. The use of borders is covered in the Swing tutorial section on JPanel. For a quick preview, however, see the following examples which use titled borders.

 

The third new feature, and the one I am focusing on here, is the ability to use HTML to format the label. The idea is that, if the string for the label begins with "<html>", then the string is interpreted as HTML rather than taken literally. This lets you make multi-line labels, labels with mixed colors and fonts, and various other fancy effects. This capability also applies to JButton. Although nice, this capabillity also has several significant limitations:

·                 JLabel label = new JLabel("<html>Bold Text");
·                 label.setFont(new Font("Serif", Font.PLAIN, 36));
        ...

Sun says that this will probably not be fixed until after the first release of JDK 1.3.

3. JLabels with HTML: Example (Download source code)

 

------------------------------------

 

-------------------------------------

 

 

The following example produces the result shown in the image above:

import java.awt.*;
import javax.swing.*;
 
public class JLabels extends JFrame {
  public static void main(String[] args) {
    new JLabels();
  }
 
  public JLabels() {
    super("Using HTML in JLabels");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    Font font = new Font("Serif", Font.PLAIN, 30);
    content.setFont(font);
    String labelText =
      "<html><FONT COLOR=RED>Red</FONT> and " +
      "<FONT COLOR=BLUE>Blue</FONT> Text</html>";
    JLabel coloredLabel =
      new JLabel(labelText, JLabel.CENTER);
    coloredLabel.setBorder
      (BorderFactory.createTitledBorder("Mixed Colors"));
    content.add(coloredLabel, BorderLayout.NORTH);
    labelText =
      "<html><B>Bold</B> and <I>Italic</I> Text</html>";
    JLabel boldLabel =
      new JLabel(labelText, JLabel.CENTER);
    boldLabel.setBorder
      (BorderFactory.createTitledBorder("Mixed Fonts"));
    content.add(boldLabel, BorderLayout.CENTER);
    labelText =
      "<html>The Applied Physics Laboratory is a division " +
      "of the Johns Hopkins University." +
      "<P>" +
      "Major JHU divisions include:" +
      "<UL>" +
      "  <LI>The Applied Physics Laboratory" +
      "  <LI>The Krieger School of Arts and Sciences" +
      "  <LI>The Whiting School of Engineering" +
      "  <LI>The School of Medicine" +
      "  <LI>The School of Public Health" +
      "  <LI>The School of Nursing" +
      "  <LI>The Peabody Institute" +
      "  <LI>The Nitze School of Advanced International Studies" +
      "</UL>";
    JLabel fancyLabel =
      new JLabel(labelText,
                 new ImageIcon("images/JHUAPL.gif"),
                 JLabel.CENTER);
    fancyLabel.setBorder
      (BorderFactory.createTitledBorder("Multi-line HTML"));
    content.add(fancyLabel, BorderLayout.SOUTH);
    pack();
    setVisible(true);
  }
}

Note: also requires WindowUtilities.java and ExitListener.java, shown earlier, plus JHUAPL.gif.


 

·         JButton

o        Basics

o        New Features: Icons, Alignment, Mnemonics, and HTML Content

o        Example

·         JPanel

o        Basics

o        New Features: Borders

o        Example

·         JSlider

o        Basics

o        New Features: Tick Marks and Labels

o        Example

·         JColorChooser

o        Basics

Example

Simple Swing Components, continued

·         Internal Frames

o        Basics

o        Example

·         Alert Dialogs (JOptionPane)

o        Basics

o        Confirm Dialog Examples

o        Message Dialog Examples

o        Interactive Dialog Creator

·         JToolBar

o        Basics

o        Making Buttons for Toolbars

o        Example

·         JEditorPane

o        Basics: Displaying HTML

o        Following Hypertext Links

o        Building A Simple Web Browser

o        HTML Support and JavaHelp

·         Other Simple Components

o        JLabel

o        JCheckBox

o        JRadioButton

o        JFileChooser

o        JTextField

o        JTextArea

Complex Swing Components

·         JList

o        General Info on MVC, Custom Data Models, and Custom Cell Renderers

o        JList with Fixed Set of Choices

o        JList with Changeable Choices

o        JList with Custom Data Model

o        JList with Custom Renderer

·         JTree

o        Basic JTree

o        Handling JTree Events

o        Custom Models and Dynamic JTrees

o        Changing the Node Icons

Other Swing Capabilities

·         Printing

o        Background

o        Printing Basics

o        The Role of Double Buffering

o        A General-Purpose Component-Printing Routine

Example