Sunteți pe pagina 1din 22

LECTURE 7 Chee Yap

JAVA SWING GUI TUTORIAL


These notes are based on the excellent book, "Core Java, Vol 1" by Horstmann and Cornell, chapter 7, graphics programming. Introduction to AWT and Swing. AWT relies on "peer-based" rendering to achieve platform independence. But subtle difference in platforms resulted in inconsistent look-and-feel, and platform-dependent bugs. Swing avoids these problems by using a non-peer-based approach, with the result it may be slower than AWT. To recover the look-and-feel of each platform (Windows, Motif, etc), it allows programs to specify the look-and-feel. It also has a new look-and-feel, called "Metal". Note that AWT is not deprecated as a result of Swing. Terminology: Component: a user interface element that occupies screen space. E.g., button, text field, scrollbar. Container: screen area or component that can hold other components. E.g., window, panel. Event Detector: (non standard terminology?) I guess most components detects events and generates a corresponding event object. This is sent to the registered "listeners" for this event(component?). [Previous Section] [Next Section]

1 First Step: JFrame


The following gives the simplest standalone application involving Java GUI:
// file: EmptyFrame.java // Adapted from Core Java, vol.1, by Horstmann & Cornell import javax.swing.*; class MyFrame extends JFrame { public MyFrame() { setTitle("My Empty Frame"); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) } public static void main(String[] args) { JFrame f = new MyFrame(); f.show(); }

You can compile and run this program but it does not do anything useful. It shows an empty window with the title "My Empty Frame". A top-level window is a "frame". The AWT library has a peer-based class called Frame. In Swing, this is called JFrame. Indeed, most of the AWT components (Button, Panel, etc) has corresponding Swing counterparts named by prepending a "J" (JButton, JPanel, etc). JFrame is

one of the few Swing components that are not drawn on a canvas. A JFrame is a "container" meaning it can contain other components such as bottons and text fields. Question: what is the relation between f.show() and f.setVisible(true)? Ans: equivalent.

2 Second Step: WindowListener


The above program is only hidden when you click the window close button. To truly kill the program, you need to type "CNTL-C". Our next program called EmptyFrame1.java will fix this problem. This brings us to the GUI interaction model. When you click the window close button, it generates a window closing event. But some object has to be a "listener" for this event, and to act upon it. The Java model requires aWindowListener object for events generated by the frame. WindowListener is an interface with 7 methods to handle events of various kinds ("window closing event" is the one of interest here). When a window event occurs, the GUI model will ask the frame to handle the event using one of these 7 methods. Suppose you have implement WindowListener with a class "Terminator" which closes your window properly. Now, all you do is register an instance of Terminator:
class MyFrame extends JFrame { public MyFrame() { addWindowListener( new Terminator()); ... } ... }

But it is tedious to write a class "Terminator" to implement WindowListener when most of these 7 methods turn out to be null. So AWT provides a default implementation called WindowAdapter(found in java.awt.event.*) where all these 7 methods are null! But you can just extend this class and write any non-null methods to override the default:
class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } }

Here is our actual code:


// file: EmptyFrame1.java import java.awt.event.*; import javax.swing.*; class EmptyFrame1 extends JFrame { // Constructor: public EmptyFrame1() { setTitle("My Closeable Frame"); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) // Window Listeners addWindowListener(new WindowAdapter() {

} ); }

public void windowClosing(WindowEvent e) { System.exit(0); } //windowClosing

public static void main(String[] args) { JFrame f = new EmptyFrame1(); f.show(); } //main } //class EmptyFrame1

Note that we did not declare the terminator class; instead we use an anonymous class:new WindowAdapter() { ... } . Remark: sometimes, you may also need to call dispose() before System.exit(0), to return any system resources. But dispose alone without System.exit(0) is not enough. [Previous Section] [Next Section]

3 Third Step: Adding a Panel


We can next add panels to frames. The program called MyPanel.java illustrates adding a panel. There are 2 steps: First, you need to define your own "MyPanel" class, which should extend the JPanel class. The main method you need to define in MyPanel is the "paintComponent" method, overriding the default method in JPanel. Second, you need to add an instance of MyPanel to the JFrame. Not just the JFrame, but to a specific layer of the JFrame. A JFrame has several layers, but the main one for adding components is called "content pane". We need to get this pane:
Container contentPane = frame.getContentPane();

Then add various components to it. In the present example, we add a JPanel:
contentPane.add( new MyPanel());

[Previous Section] [Next Section]

4 Fourth Step: Fonts in Panels


We next address the issue of fonts. Font families have several attributes: Font name. E.g. Helvetica, Times Roman Font style. E.g., PLAIN, BOLD, ITALIC Font size. E.g., 12 Point
Font helv14b = new Font("Helvetica", Font.BOLD, 14);

To construct a Font object, do

To use the font, call the setFont() method in the graphics object g: g.setFont(helvb14);You can also specify font styles such asFont.BOLD + Font.ITALIC. Use getAvailableFontFamilyNames of GraphicsEnvironment class to determine the fonts you can use. Instead of Font names, AWT defines 5 "logical font names":

SansSerif, Serif, Monospaced, Dialog, DialogInput

which are always available. These concepts are illustrated below in our elaboratedpaintComponent method. The goal is ostensibly to print "Hello" in bold and "World!" in bold-italic fonts. To do this, we need to get the FontMetrics object which has methods to measure the length and height of a string, say.
/************************************************************* * @file: TextPanel.java * @source: adapted from Horstmann and Cornell, Core Java * @history: Visualization Course, Spring 2003, Chee Yap *************************************************************/ import java.awt.*; import java.awt.event.*; import javax.swing.*; /************************************************************* * TextPanel Class (with main method) *************************************************************/ class TextPanel extends JPanel { // override the paintComponent method // THE MAIN DEMO OF THIS EXAMPLE: public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("SansSerif", Font.BOLD, 14); Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14); FontMetrics fm = g.getFontMetrics(f); FontMetrics fim = g.getFontMetrics(fi); int cx = 75; int cy = 100; g.setFont(f); g.drawString("Hello, ", cx, cy); cx += fm.stringWidth("Hello, "); g.setFont(fi); g.drawString("World!", cx, cy); } //paintComponent //============================================= ///////////// main //////////////////////////// public static void main(String[] args) { JFrame f = new MyFrame("My Hello World Frame"); f.show(); } //main } //class TextPanel /************************************************************* MyFrame Class *************************************************************/ class MyFrame extends JFrame { public MyFrame(String s) { // Frame Parameters

setTitle(s); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) // Window Listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } //windowClosing }); //addWindowLister // Add Panels Container contentPane = getContentPane(); contentPane.add(new TextPanel()); } //constructor MyFrame } //class MyFrame

NOTE: The java.awt.FontMetrics.* class also has methods to get other properties of the font: its ascent, descent, leading, height, etc. [Previous Section] [Next Section]

5 Fifth Step: Basic Graphics


In "DrawFrame.java", we do basic 2D-graphics. We use the following primitives: drawXXX where XXX = Polygon, Arc, Line. We also use the "fillXXX" versions. Important point: in java.awt, you need to use a "canvas" to draw. In "Swing", you draw on any kind of panel. More Basic Graphics In "DrawFrame1.java", we further look at the primitives drawXXX where
XXX = Rect, RoundRect, Oval.

We also replace "drawXXX" by "fillXXX". [Previous Section] [Next Section]

6 6th Step: Basic Event Handling


This is shown in ButtonFrame.java demo. We consider the class vent", which are all derived from java.util.EventObject. Examples of events are "button pushed", "key pushed", "mouse moved". Some subclasses of Event are ActionEvents and WindowEvents. To understand events, you need to consider two types of interfaces, and their relationship:Event Detectors and Event Listeners. The former is set up to detect the occurence of certain types of event, and it sends notices to the listeners. It is the listeners that take the appropriate action. Examples of Event Detectors are windows or buttons. In this first event demo, we use buttons, as they generate the simplest kind of events. Buttons detects only one type of event - called ActionEvents. In contrast, there are seven kinds of WindowEvents. For buttons, the ctionListener" is appropriate. But in order for the event objects to know which listener object to send the events to, we need to do three things:

(1) Implement the listener interface using ANY reasonable class. In our example, the class will be an extension of JPanel. To implement the ActionListener, you need to supply the method actionPerformed(ActionEvent) (the only method of this interface). The class for implementing Actionlistener here is "MyPanel":
public class MyPanel extends JPanel implements ActionListener { public void actionPerformed(ActionEvent e){ // reaction to button click goes here ... } // actionPerformed } // class MyPanel

What is the action "..." above? This is explained below. (2) Create a listener object:
Listener lis = new MyPanel();

(3) register this object with the event detector.


detector; button.addActionListener(lis); // button is the event

The general form for registering listener objects is:


<eventDetector>.add<EventType>Listener(<listenerObject>);

In our present demo, we will have two buttons (redButton and blueButton) in a panel. When redButton is pressed, the background of the panel changes to Red, and similarly when the blueButton is pressed. Thus, these buttons serve as event detectors. To use buttons, we need to create them:
private JButton redButton; redButton = new JButton("RED"); // "RED" is label on button

In addition to (or instead of) "RED", we can supply an image file:


redButton = new JButton(new ImageIcon("RED.gif");

Next, you add the buttons to a panel (called ButtonPanel here). We also register the listener object with the buttons - but the listener object will be "this" (i.e., current object)!
class ButtonPanel extends JPanel { // members: private JButton redButton; private JButton blueButton; // constructors: public ButtonPanel() { // create buttons redButton = new JButton("RED"); blueButton = new JButton("BLUE"); // add buttons to current panel add(redButton); // add button to current panel

add(blueButton); // add button to current panel // register the current panel as listener for the buttons redButton.addActionListener(this); blueButton.addActionListener(this); } // ButtonPanel constructor } // ButtonPanel class

We now return the details needed in the ctionPerformed(ActionEvent)" method from the ActionListener interface. First, you need to find out which Button caused this event. There are 2 ways to find out. First, the getSource() method from EventObject can be used:
Color color = getBackground(); // color will be set Object source = e.getSource(); if (source == redButton) color = Color.red else if (source == blueButton) color = Color.blue setBackground(color); repaint(); // when do we need this??

The second method, specific to ActionEvents, is to use the getActionCommand() method, which returns a "command string", which defaults to the button label. Thus,
String com = e.getActionCommand(); if (com.equals("RED")) ...; // "RED" is the label of redButton else if (com.equals("BLUE")) ...;

But the command string need not be the label of the button. That can be independently set:
redButton.setActionCommand("RED ACTION");

The ActionListener interface is also used when (a) when an item is selected from a list box with a double click, (b) when a menu item is selected (c) when an enter key is clicked in the text field (d) when a specific time has elapsed for a "Timer" component. In our present example of the red and blue buttons, the ActionListener interface is implemented by MyPanel for a good reason: the action of changing the background of the panel to red or blue ought to reside with the panel! [Previous Section] [Next Section]

7 7th Step: Window Events


(NO DEMO PROGRAM HERE! FIX) We now consider the JFrame as an event detector. A JFrame is basically synonymous with a "window" and it detect Window Events. We need to implement the "WindowListener" interface to be registered with the JFrame. This interface has 7 methods:
public public public public public public public void void void void void void void windowClosed(WindowEvent e) windowIconified(WindowEvent e) windowOpened(WindowEvent e) windowClosing(WindowEvent e) windowDeiconified(WindowEvent e) windowActivated(WindowEvent e) windowDeactivated(WindowEvent e)

Recall that we already had a brief introduction to this interface, when we extended the "WindowAdapter" class to provide default empty implementations for all but the windowClosing method, which we implement by a call to "System.exit(0)". In Step 2 above, the extension of WindowAdapter was called Terminator. In general, all the AWT listener interfaces with more than one method comes with such an adapter class. Finally, we we create an instance of the Terminator class and register it with the JFrame using the ddWindowListener(WindowListener wl)" method:
class MyFrame extends JFrame { // Constructor: public MyFrame() { addWindowListener(new Terminator()); ... } // MyFrame Constructor ... } // MyFrame Class

We can even make the "Terminator" anonymous, as an inner class, as follows:


class MyFrame extends JFrame { // Constructor: public MyFrame() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } // windowClosing }); // WindowAdapter ... } // MyFrame Constructor ... } // MyFrame Class

In general, you can create an anonymous class by the construct


new XXXclass() {... override methods, etc... }

where XXXclass is the class name. Inner classes are also extremely useful, because the inner class can automatically get access to all the methods and fields of its parent class. In Component design, you often want a new class to subclass two different classes. But Java does not allow this. You get around this restriction by subclassing a subclass - an inner class is one way of doing this. An example where you want to program the "windowDeactivated", "windowActivated", "windowIconified" and "windowDeiconified" is when your window displays an animation. You would want to stop or start the animations when these events occur. [Previous Section] [Next Section]

8 8th Step: Event Classes and Listener Interfaces


Now that we have seen two types of events (ActionEvents and WindowEvents), let us overview the general picture. Here is the event hierarchy:
| ActionEvent* | ContainerEv.* | AdjustmentEv.* | FocusEvent* | KeyEvent* EventObject <-- AWT Event <--| ComponentEv.* <--| InputEvent <--|

| ItemEvent* | TextEvent*

| PaintEvent | WindowEvent*

| MouseEv.*

In this hierarchy, only 10 event classes, those indicated with asterisks (*) are actually passed to listeners. The 10 event classes are classified into 4 emantic" events and 6 "low-level" events. Intuitively, semantic events correspond to what the user intends (e.g., button click), while lowlevel events correspond to physical events. Semantic Events 1) ActionEvent: button click, menu selection, selecting item in list, typing ENTER in text field 2) AdjustmentEvent: the user adjusted a scroll bar. 3) ItemEvent: the use made a selection from a set of checkbox or list items 4) TextEvent: the contents of a text field or area were changed. Low-Level Events 1) ComponentEvent: component is resized, moved, shown, hidden. It is the base class for all low-level events. 2) KeyEvent: a key was pressed or released. 3) MouseEvent: the mouse button was depressed, released, moved, dragged. 4) FocusEvent: a component got focus, lost focus. 5) WindowEvent: window was (de)activated, (de)iconified, or closed. 6) ContainerEvent: a component has been added or removed. Usually, you don't have to worry about this class of event, as these events are (usually) not generated dynamically, but in your program. All low-level events is derived from ComponentEvent. They all have a method "getComponent" (it is similar to the "getSource" method but the result is already cast as a component). There are 11 listener interfaces in java.awt.event:
ActionListener, ContainerListener*, MouseMotionListener*, ItemListener, AdjustmentListener, KeyListener*, TextListener, WindowListener*. ComponentListener* MouseListener* FocusListener*

The listeners with asterisks (*) have a corresponding adaptor class implementing it because they each have more than one method. There is a 1-1 correspondence between listeners and event types, with one exception: MouseEvents are sent to both MouseListeners and MouseMotionListener. The split into two types of listeners for MouseEvents is done for efficiency - so we can ignore an entire class of mouse events (such as mouse motion which can generate frequent events). [Previous Section] [Next Section]

9 9th Step: Focus Event


(NO DEMO PROGRAM HERE) (A) In Java, a component has the "focus" if it can receive key strokes. E.g., a text field has the focus when the cursor mark becomes visible, ready to receive key strokes. When a button has "focus", you can click it by pressing the space bar. (B) Only one component can have the focus at any moment. The user can choose the component to have focus by a mouse click in the component (in some system, just having the mouse cursor over a component is sufficient). The TAB key also moves the focus to the "next" component, and thus allows you to cycle over all "focusable" components. Some components like labels or panels are

not "focusable" by default. You can make any component "focusable" or not by overriding the sFocusTraversable" method to return TRUE or FALSE. You can use the "requestFocus" method to move the focus to any specific component at run time, or you can use "transferFocus" method to move to the next component. The notion of "next" component can be changed. (C) The FocusListener interface has 2 methods: focusGained and focusLost. Each takes the "FocusEvent" object as parameter. Two useful methods for implementing this interface are "getComponent" and sTemporary". The latter returns TRUE if the focus lost is temporary and will automatically be restored. [Previous Section] [Next Section]

10 10th Step: KeyBoard Events and Sketch Demo


The "keyPressed" and "keyReleased" methods of the KeyListener interface handles raw keystrokes. However, another method "keyTyped" combines the response to these two types of events, and returns the characters actually typed. Java distinguished between "characters" and "virtual key codes". The latter are indicated by the prefix of "VK_" such as "VK_A" and "VK_SHIFT". These 3 methods are best illustrated with an example: Suppose a user types an lower case ". There are only 3 events: (a) Pressed A key (keyPressed called for VK_A) (b) Typed " (keyTyped called for character ") (c) Released A key (keyReleased called for VK_A) Now, suppose the user types an upper case ". There are 5 events: (a) Pressed the SHIFT key (keyPressed called for VK_SHIFT) (b) Pressed A key (keyPressed called for VK_A) (c) Typed " (keyTyped called for character ") (d) Released A key (keyReleased called for VK_A) (e) Released SHIFT key (keyReleased called for VK_SHIFT) To work with keyPressed and keyReleased methods, you need to check the "key code".
public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); ... }

The key code (defined in the KeyEvent class) is one of the following constants:
VK_A VK_B ... VK_Z VK_0 ... VK_9 VK_COMMA VK_PERIOD ... etc

Instead of tracking the key codes in the case of combination strokes, the following methods which returns a Boolean value are useful: "KeyEvent.isShiftDown()", "KeyEvent.isControlDown()", "KeyEvent.isAltDown()" and "KeyEvent.isMetaDown()". To work with keyTyped method, you can call the "getKeyChar" method. The following demo is a tch-A-Sketch" toy where you move a pen up, down, left, right with cursor keys or h, j, k, l. Holding down the SHIFT key at the same time will move the pen by larger increments. [Previous Section] [Next Section]

11 11th Step: Mouse Events and Mouse Demo


Some mouse events such as clicking on buttons and menus are handled internally by the various components and translated automatically into the appropriate semantic event (e.g, handled by the actionPerformed or itemStateChanged methods). But to draw with a mouse, we need to trap mouse events. When the user clicks a mouse button, three kinds od MouseEvents are generated. The corresponding three MouseListener methods are: "mousePressed", "mouseReleased" and "mouseClicked". The last method generates only one event for each pressed-released combination. To obtain the position of the mouse when the events occur, use the methods MouseEvent.getX() and MouseEvent.getY(). To distinguish between single and double (and even triple) clicks, use the MouseEvent.getClickCount() method. SIMPLIFY the example in the book (how about drawing a line to the current mouse click?) But I already have this under the "rubber line" example. [Previous Section] [Next Section]

12 12th Step: Action Interface


(I) WHAT ARE ACTIONS? Java even model allows us to choose any class as listener for its events. So far, we have let each class (i.e., "this") be its own listener. For bigger examples, we want to separate the responsibilites of detecting from listening/responding. We need an independent notion of ction" (="responding to action"). This is logically sensible, since the same action may be needed for different events. For example, suppose the action is to et background color" (to red/blue, etc). This action may be initiated in 3 ways: (a) click on a color button (as in example above) (b) selection of a color in a set-background menu (c) press of a key (B=blue, R=red, etc). (II) METHODS OF ACTION INTERFACE: Java provides the ction" interface with these methods: (1) void actionPerformed(ActionEvent e) - performs the action corresponding to event e (2) void setEnabled(boolean b) - this turns the action on or off (3) boolean isEnabled() - checks if the action is on (4) void putValue(String key, Object val) - store a value under a key (String type). There are 2 standard keys: Action.NAME (name of action) and Action.SMALL_ICON (icons for action). E.g., Action.putValue(Action.SMALL_ICON, new ImageIcon("red.gif")); (5) Object getValue(String key) - retrieve the value stored under key (6) void addPropertyChangeListener(PropertyChangeListener listener) - Add a "Changelistener" object to our current list. Menus and toolbars are examples of "ChangeListeners", as these components must be notified when a property of an action that they are responsible for changes. (7) void removePropertyChangeListener(PropertyChangeListener listener) - Similar to method in (6), but this one is to remove a "ChangeListener" from current list. Actually, ction" extends ctionListener" and method (1) above was the ONLY method in the ActionListener interface (cf. the ButtonFrame.java demo above). This method Thus, an Action object can be used whenever an ActionListener object is expected. (III) MenuAction.java: IMPLEMENTING and USING AN ACTION INTERFACE. There are three steps: STEP 1: Define a class implementing the Action interface

STEP 2: Instance the Action class STEP 3: Associate the action instance with components STEP 4: Add the components to the windowing system STEP 1: As usual, there is a default implementation of the Action interface, called bstractAction". You can adapt from this class, and only ctionPerformed" method needs to be explicitly programed by you. Usually, you also want to provide a constructor to set the values stored under various keys, and your class will want a member variable "target" to remember the component where the action is to be performed (recall that the Action object need not be the component itself, after our decoupling of vent generator" from vent listener"). Here is an implementation of the action et background color":
class BackgroundColorAction extends AbstractAction { //members: private Component target; // where you want the action done! //constructor: public BackgroundColorAction( String name, Icon i, Color c, Component comp) { putValue(Action.NAME, name); putValue(Action.SMALL\_ICON, i); putValue("Color", c); target = comp; } // constructor //methods: public void actionPerformed(ActionEvent e) { Color c = (Color)getValue("Color"); target.setBackground(c); target.repaint(); }// actionPerformed method }// BackgroundColorAction class

STEP 2: we need to instance the class:


Action redAction = new BackgroundColorAction( "Red", new ImageIcon("red.gif"), Color.red, panel);

STEP 3: associate the action with components or their instances: The following associates "redAction" with a component instance. The component illustrated here is a JButton instance.
JButton redButton = new JButton("Red"); redButton.addActionListener(redAction);

Alternatively, we associate any given ction" with an entire class of components. For JButtons, we create button class that comes with an action:
class ActionButton extends JButton { public ActionButton(Action a) { setText((String)a.getValue(Action.NAME)); Icon icon = (Icon)a.getValue(Action.SMALL\_ICON); if (icon != null) setIcon(icon) addActionListener(a); }// ActionButton constructor }// ActionButton class

// instance it! redButton = new ActionButton(redAction);

NOTE: If we introduce ctionButtons" then STEPS 2 and 3 should be interchanged! STEP 4: Now add ActionButtons to a menu, then to the menu bar:
// create the menu of ActionButtons: JMenu m = new JMenu("Color"); m.add(redAction); m.add(blueAction); // add menu to menubar JMenuBar mbar = new JMenuBar(); mbar.add(m); setJMenubar(mbar);

[Previous Section] [Next Section] Go to Top of Page

File translated from TEX by TTH, version 3.01.

On 30 Apr 2003, 17:43.

Tutorial 10 - Swing GUI Widgets

A Graphical User Interface (GUI) is a visual paradigm which allows a user to communicate with a program in an intuitive way. Its main features are widgets (aka controls) and event driven activities. Application users expect a graphical interface. The next few tutorials will introduce Java's GUI widgets as well as some layout design considerations. One reference with lots of examples can be found in the Guidebook.Swing Sightings demos Swing in significant applications. Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing. AWT uses the native operating system's window routines so the visual effect is dependent on the run-time system platform. But this is contrary to the concept of having a virtual model. Swing allows three modes: a unified look and feel [the default], the native platform look, or a specific platform's look. Swing is built on the original objects and framework of AWT. Swing components have the prefix J to distinguish them from the original AWT ones (eg JFrame instead of Frame). To include Swing components and methods in your project you must import the java.awt.*, java.awt.event.*, and javax.swing.* packages. Intermediate|Advanced
Containers,Wind Dialog Ba

ows,Panes JFrame and JPanel

Boxes Labels,Ico ns,Buttons

sic Ev en t Lis te ne rs Bo un de dRa ng e Co m po ne nt s

Containers, Windows and Content Panes


Containers are components that are used to hold and groupwidgets such as text fields and checkboxes and other components. Methods common to many containers include: add(), pack(), requestFocus() and setToolTipText(). Windows are top-level containers which interface to the operating system's window manager. Their types are:Primary (adorned with minimize, maximize and close buttons) [JFrame]; Secondary [JDialog];Plain (no border - used for splash screens) [JWindow] and XHTML document [JApplet]. Content panes are intermediate containers such asJPanel, JOptionPane,JScrollPane,JLayeredPane,JSplitPane and JTabbedPane which organize the layout structure when multiple controls are being used. JInternalFrame is an adorned lower-level frame used with MDI (Multiple Document Interface). It prevents overlapping of the documents.

JFrame and JPanel


JFrame is the most commonly used top-level container. It adds basic functionality such as minimize, maximize, close, title and border to basic frames and windows. Some important JFrame methods are: getTitle(), setBounds(x,y,w,h), setLocation(x,y), setMaximumSize(w,h), setMinimumSize(w,h), setPreferredSize(w,h), setResizable(bool), setSize(w,h) and setTitle(str). setVisible(bool) replaces the deprecated show() method. The setDefaultCloseOperation(constant) method controls the close icon action. The constant normally is EXIT_ON_CLOSE. JPanel is the most commonly used content pane. An instance of the pane is created and then added to a frame. The add(widgetName)method allows widgets (ie GUI controls) to be added to

the pane. The way they are added is controlled by the current layout manager. JPanel defaults to FlowLayout. All other content panes default to BorderLayout. The following is a simple template that creates a JFrame container class using inheritance. The created subclass then adds a JPanel. This custom class will form the basis of many of our GUI examples.
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame1 extends JFrame { JPanel pane=new JPanel(); Frame1() // the frame constructor method { super("My Simple Frame"); setBounds(100,100,300,100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); // add the panel to frame // customize panel here // pane.add(someWidget); setVisible(true); // display this frame } public static void main(String args[]) {new Frame1();} }

Dialog Boxes
Dialogs are short messages, confirmationsor input prompts for simple string information which appear as popup windows. Dialogs can either be modal (must be dismissed before another window is accessed) or modeless. JOptionPane provides a modal dialog with predefined methods for each type of dialog. Each JOptionPane method has a first parameter that points to a parent (ie. window that it appears in) or null (default to the current window). The second parameter is the message or prompt to be displayed. New instances of JOptionPane are not normally generated. showMessageDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. The dialog has a single 'ok' button for completion and no data is returned by this method.
JOptionPane.showMessageDialog(null,"This is just a message", "Message Dialog",JOptionPane.PLAIN_MESSAGE);

showConfirmDialog() has three more optional parameters to set a dialog title, alter the button display, and select the dialogs icon. By default there are three buttons 'Yes', 'No' and Cancel for dialog completion. The returned value is one of JOptionPane.YES_OPTION, JOptionPane.NO_OPTION or JOptionPane.CANCEL_OPTION.
pressed=JOptionPane.showConfirmBox(null,"Everything aok"); if (pressed==JOptionPane.YES_OPTION) { // do the action for confirmation }

showInputDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. There is both an 'ok' button and a 'cancel' button for dialog completion. Any information typed into the entry box is returned as a string.

user_data=JOptionPane.showInputDialog(null,"What's your name");

The list of icon types that can be displayed (by predefined constant) contains ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, and WARNING_MESSAGE. JDialog provides a simple unadorned window used to create customized dialog boxes. Customization can include modality and mnemonics (aka hotkeys).

Labels, Icons and Buttons


Labels are non-interactive text objects most commonly used as prompts. They are created using the JLabel() constructor with the required text as the first parameter. Another parameter can be added using a SwingConstant value to set horizontal alignment. Vertical alignment is through the setVerticalAlignment() method. The contents of a label can be changed with the setText() method. Icons can be easily added to labels or other controls either to brand, dress up, or aid accessibility. Icons are constructed from the ImageIcon class and then added as a parameter to the label (or other) control. An extra parameter can be used to control theposition of the text relative to the icon. It must use one of the SwingConstants values.
ImageIcon icon=new ImageIcon("smile.gif"); JLabel label=new JLabel("hello",icon,SwingConstants.RIGHT); pane.add(label);

Buttons are created with the JButton() constructor and are used to start operations. They can be deactivated with thesetEnabled(false) method and tested with the isEnabled()method. A useful method is setMnemonic(char) which allows a hot key to be associated with the button. Simple buttons require anActionEvent event listener that reacts to the button click. Many GUIs use an array set of buttons. CheckBgui for a demo of this technique. Toggle buttons are a visual push on - push off mechanism. They are created with the JToggleButton() constructor. The isSelected() method returns the state of the button. In addition to ActionEvent, the ChangeEvent is triggered.
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame2 extends JFrame { JPanel pane=new JPanel(); JButton pressme=new JButton("Press Me"); Frame2() // the frame constructor { super("JPrompt Demo"); setBounds(100,100,300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); // JPanel containers default to Flow Layout pressme.setMnemonic('P'); // associate hotkey to button pane.add(pressme); pressme.requestFocus(); setVisible(true); // make frame visible } public static void main(String args[]) {new Frame2();} }

Basic Event Listeners

GUIs are event-based as they respond to buttons, keyboard input or mouse activities. Java uses event listeners to monitor activity on specified objects and react to specific conditions. Check theappendix for a listing of event listeners. View advanced event listeners for techniques on organizing many different events in larger projects. The first step in adding a basic button push event handler to the above example is to import awt.event.* which contains all of the event classes. Next add the phrase implements ActionListenerto the class header to use the interface. Register event listeners for each button widget using theaddActionListener(this) method. The reserved word thisindicates that the required (by implements ActionListener) handler method called actionPerformed() will be included in the current class. For example:
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame3 extends JFrame implements ActionListener { JLabel answ er=new JLabel(""); JPanel pane=new JPanel(); // create pane object JButton pressme=new JButton("Press Me"); Frame3() // the constructor { super("Event Handler Demo"); setBounds(100,100,300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); pressme.setMnemonic('P'); // associate hotkey pressme.addActionListener(this); // register button listener pane.add(answ er); pane.add(pressme); pressme.requestFocus(); setVisible(true); // make frame visible } // here is the basic event handler public void actionPerformed(ActionEvent event) { Object source=event.getSource(); if (source==pressme) { answ er.setText("Button pressed!"); JOptionPane.show MessageDialog(null,"I hear you!", "Message Dialog",JOptionPane.PLAIN_MESSAGE); setVisible(true); // show something } } public static void main(String args[]) {new Frame3();} }

Bounded-Range Components
Bounded-range components are controls that have a single integer value within fixed integer boundaries. Examples of bounded-range controls are progress bars. sliders and scroll bars. Each bounded-range component has the following methods: setExtent(), setMaximum(), setMinimum(), setValue(), getValueIsAdjusting()and setOrientation(). Bounded-range components useChangeEvent to start an update. Progress bars indicate status for time consuming jobs. The basic JProgressBar class offers a subtle control. If you want a dialog frame for canceling an operation the classes,ProgressMonitor and ProgressMonitorInputStreamare better choices.

ProgressMonitorInputStream is a stream filter in addition to a progress monitor. ProgBar.java is a simple progress bar demo. Sliders allow integer selection within limits. They can be dressed up with ticks and labels using setPaintTicks(true)and setPaintLabels(true). setMajorTickSpacing(int)and setMinorTickSpacing(int) set the intervals used for marker ticks. setSnapToTicks(true) forces the slider to the closest tick. setInverted(true) reverses the low and high marks.labelTable is a dictionary of slider values and Jlabel objects for painting the object. Slider.javais a simple slider demo. Java Swings Tutorial
What is Swings in java ? A part of The JFC Swing Java consists of Look and feel Accessibility Java 2D Drag and Drop, etc Compiling & running programs javac <program.java> && java <program> Or JCreator / IDE if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen. Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT. Swing Model/view design: The view part of the MV design is implemented with a component object and the UI object. The model part of the MV design is implemented by a model object and a change listener object. <br /><font size=-1> Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.

100% Java implementation of components Pluggable Look & Feel Lightweight components Uses MVC Architecture Model represents the data

View as a visual representation of the data Controller takes input and translates it to changes in data Three parts Component set (subclasses of JComponent) Support classes Interfaces

In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing twice as many as in AWT. Java Swing class hierarchy The class JComponent, descended directly from Container, is the root class for most of Swings user interface components.

Swing contains components that youll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required.

Java Swing Examples


Below is a java swing code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a java program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse. import javax.swing.JFrame; import javax.swing.JLabel; //import statements //Check if window closes automatically. Otherwise add suitable code public class HelloWorldFrame extends JFrame {

} Output

public static void main(String args[]) { new HelloWorldFrame(); } HelloWorldFrame() { JLabel jlbHelloWorld = new JLabel("Hello World"); add(jlbHelloWorld); this.setSize(100, 100); // pack(); setVisible(true); }

Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.

JPanel is Swings version of the AWT class Panel and uses the same default layout,

FlowLayout. JPanel is descended directly from JComponent.

JFrame is Swings version of Frame and is descended directly from that

class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.

JInternalFrame is confined to a visible area of a container it is


placed in. It can be iconified , maximized and layered.

JWindow

is Swings version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default.
JDialog is Swings version of Dialog and is descended directly from that class. Like

Dialog, it uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some of the most common dialogs are provided through static methods in the class JOptionPane.

JLabel, descended from JComponent, is used to create text labels.


The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including

JButton.

JTextField allows editing of a single line of text. New features include the
ability to justify the text left, right, or center, and to set the texts font.

JPasswordField (a direct subclass of JTextField) you can suppress


the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.

JTextArea

allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying

JScrollPane can be forced to always or never have either the vertical or


horizontal scrollbar; JButton is a component the user clicks to trigger a specific action.

JRadioButton is similar to JCheckbox, except for the default icon for


each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected.

JCheckBox

is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state.

JComboBox JList

is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entrys name selects that entry. A vertical scrollbar is used for longer lists. provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener.

JTabbedPane contains a tab that can have a tool tip and a mnemonic,
and it can display both text and an image.

JToolbar contains a number of components whose type is usually some


kind of button which can also include separators to group related components within the toolbar.

FlowLayout when used arranges swing components from left to right


until theres no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more.

BorderLayout

places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas.

GridLayout is a layout manager that lays out a containers components


in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

GridBagLayout is a layout manager that lays out a containers


components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.

JMenubar

can contain several JMenus. Each of the JMenus can contain a series of JMenuItem s that you can select. Swing provides support for pull-down and popup menus.

Scrollable JPopupMenu is a scrollable popup menu that


can be used whenever we have so many items in a popup menu that exceeds the screen visible height.

Java Swing Projects

Java Swing Calculator

developed using Java Swing. It is a basic four-function calculator java program source code.

Java Swing Address Book demonstrates how to create a

simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).

S-ar putea să vă placă și