Вы находитесь на странице: 1из 65

Swings

Types of inner classes


An inner class is a class declared inside another class
The class that encloses it is called the outer or top-level class.

A normal class is a direct member of a package; inner classes are not. Local classes
declared within a block of code and are visible only within that block, just as any other method variable.

Anonymous classes
A class with no name

Static member classes Member classes Local classes Anonymous classes

Inner Classes
An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class members, including those marked private. To instantiate an inner class, you must have a reference to an instance of the outer class.

Inner Classes
From code within the enclosing class, you can instantiate the inner class using only the name of the inner class, as follows: MyInner mi = new MyInner(); From code outside the enclosing class instance methods, you can instantiate the inner class only by using both the inner and outer class names, and a reference to the outer class as follows: MyOuter mo = new MyOuter(); MyOuter.MyInner inner = mo.new MyInner(); From code within the inner class, the keyword this holds a reference to the inner class instance. MyOuter.this;

Advantages of using Nested/Inner class.

More object oriented structure.

Package barrier is broken You are now allowed to have top-level nested classes inside another object. With inner class, you no longer have to create separate .java file for every distinct object in you program, you can integrate one object into another. This can help make the code much easier to understand.

Advantages of using Nested/Inner class.


Inner class are also very useful when you want to implement callbacks.

If you try to implement the callback procedure without inner class, then you will have to implement the ActionLlistener interface in a class and this would force you to use a bunch of if and else if to figure out on which object the event occurred.
Using inner classes allows you to efficiently have a separate bloc of code to do handle the actionPerformed function for every graphic component object.

Nested Class
These are considered to be top-level classes They have the same behavior as any static member of a class.

Can be accessed initializing the parent class,


Nested classes can access the parent class static methods and variables . Nested classes are defined with the keyword static Instantiating a static nested class requires using both the outer and nested class names as follows: BigOuter.Nested n = new BigOuter.Nested(); A static nested class cannot access nonstatic members of the outer class, since it does not have an implicit reference to any outer instance All Innerclasses are nested classes but not all nested classes are innerclass.

Nested Classes
class MyOuter { public static class MyInner { //... public void function1() {} //more function (static and more) } }

Member inner classes


They are defined as members of the enclosing class, They are defined on the same level as function and variables of a class, They have the same behavior and properties.

class MyOuter { private float variable = 0; public void outermethod() { } private class MyInner { public void innerfunction() { } public void function() { MyOutter.this.outermethod(); } } } The inner class MyInner class is a Member inner class To distinguish between the inner class's methods/fields and that of the containing class, we use "ContainingClass.this

Local Inner Classes


A method-local inner class is defined within a method of the enclosing class. To use the inner class ,it must instantiate it, and that instantiation must happen within the same method, but after the class definition code. A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final.

The only modifiers you can apply to a method-local inner class are abstract and final.

Local inner classes


This type of inner class is defined inside a bloc of code. They can live beyond the scope of the bloc of code inside witch they are defined,

Interface MyInterface { public String getInfo(); } class MyOuter { MyInterface current_object; public void setInterface(String info) { class MyInner implement MyInterface { private String info; public MyInner(String inf) {info=inf;} public string getInfo() {return info;} } current_object = new MyInner(info); } } In the example above, the class MyInner is a local inner class

Anonymous classes
A class with no name, which is why its called an anonymous class Combines the following into one step:
class declaration creation of an instance of the class

Anonymous objects cannot be instantiated from outside the class in which the anonymous class is defined
it can only be instantiated from within the same scope in which it is defined

Why use an anonymous class?


It lessens the amount of .java files necessary to define the application.
anonymous classes can access the static and instance variables of the enclosing outer class.

Can be time-savers Useful when implementing listeners in GUI programs

Anonymous classes
When you compile classes that contain anonymous classes, the compiler will create these class files:
ClassName$SomeNumber SomeNumber is the sequence number for the anonymous class

So, if you have a class named MyAnonTest.java that contains two anonymous classes, the following class files will be generated by the compiler:
MyAnonTest.class, MyAnonTest$1.class and MyAnonTest$2.class

Example Anonymous Class


class Outer extends java.awt.Frame { public Outer() { java.awt.Button button = new java.awt.Button("Click on me"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("You clicked"); } }); } } In the code above the class ActionListener is an anonymous class

Rules for Anonymous classes


An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause An anonymous class must implement all the abstract methods in the super class or the interface. An anonymous class always uses the default constructor from the super class to create an instance

Anonymous inner classes


Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. An anonymous inner class is always created as part of a statement, so dont forget to close the statement after the class definition, with a curly brace. Curly brace followed by a semicolon in Java !!. An anonymous inner class reference are those defined in the reference variable class (or interface), An anonymous inner class can extend one subclass, or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous

Anonymous inner classes


Inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface. An argument-local inner class is declared, defined, and automatically instantiated as part of a method invocation. The class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });

When to use Outer Classes


In general
Use when you need to reuse the class across several applets/applications/objects Remember to keep back-pointer(s)

Outer Classes in the Same File


Use when you're lazy or if you want to keep everything in the same file. Use when you don't need to reuse the class outside the file. Not really recommended.

When to use Inner Classes


In general
Use when you do NOT need to reuse or extend the class outside the containing class. e.g., for handling events that are specific to that applet

Non-Anonymous Inner Classes


Use when you create several different instances of the same inner class within the same applet
e.g., MoverButton

Anonymous Inner Classes


Use when you only need one instance of that class and never need to reuse it. Remember the Rule: limit code to 1 or 2 lines!
if you need more, put it in a method of the applet or use a non-anonymous inner class

Swings
Objectives:
GUI-based program using Java's Swing packages. Swing component classes. Container classes, such as frames and panels Layout managers and organizing components. Listener classes to handle events associated with components. Apply the model/view/controller pattern to the design of a program. User interfaces for dialogs and applets as well as applications.

What is Swing
Swing is a GUI toolkit to enable enterprise development in Java. Swing can be used to create large-scale Java applications with a wide array of powerful components. Component can be easily extend or modified to control their appearance and behavior. Swing is part of a larger family of Java products known as the Java Foundation Classes ( JFC),

Java Foundation Class


AWT
GUI toolkit shipped with all versions of the JDK Swings use the lightweight component facilities

Accessibility
Accessibility tools can be used in conjunction with devices such as audible text readers or braille keyboards to allow direct access to the Swing components

2D API
The 2D API contains classes for implementing various painting styles, complex shapes,fonts, and colors.

Drag and Drop


The user is allowed to click and "hold" a GUI object, moving it to another window or frame in the desktop with predictable results. Can implement droppable elements that transfer information between Java applications and native applications.

The Swing Philosophy


CATEGORIES GUI Component Classes WHAT THEY DO GUI components include basic windows objects as buttons , text fields and menu Items. Also includes are frames, applets and dialogs, which act as containers for the basic window objects When objects such as buttons are added to a window, their placement is determined by a layout manager. Eg: GridBag Layout,flow,border,grid and card Event classes define the events that are triggered when users do such things as click buttons, select menu times and move the mouse Listener classes contain methods that are activated when events occur.

Layout Manager classes

Event Classes

Listener classes

GUI Components

The first category of classes used in developing windows-based applications is the GUI components. The visible objects that constitute a window fall into this category. These objects include: Buttons text fields text areas Lists menu items and so forth

GUI Components

The Component Class Hierarchy


All of the GUI component classes, whether in Swing or AWT, are subclasses of an abstract class in AWT called Component. This class specifies the most basic attributes and behavior of all GUI objects. Every component has attributes that define its:
size (width and height in pixels) background color foreground color text font and visibility.

GUI Components

GUI Components

GUI Components

Container Classes
Container objects are so called because they contain other window objects, including other containers.
A container must use a layout manager that determines the arrangement of the components within it.

GUI Components

GUI Components
CONTAINER CLASS JFrame WHAT IT DOES Displays component in an application window. Stand alone GUI applications must extend JFrame

JApplet

Displays components in a Web browser. Applets have neither a menu bar nor a border. All web-based applications must extend JApplet
Displays components in a dialog window. Dialogs are used as auxiliary windows in stand-alone applications and applets.

JDialog

JPanel

Organizes a set of components as a group. Panels can factor complex interfaces into modular chucks, An applet, frame or dialog can contain several panels, which in can contain buttons,text fields, lists and so forth and even other panels

Containment Hirearchy
Top level containers are the root of a containment hierarchy. Interface between the native windowing environment and window manager and java application or applet JApplet, JFrame and JDialog contain a JRootPane which contains a contentPane container. components and layout managers must be added and set to the content pane not JApplet, JFrame or JDialog. (else exception thrown)

Heavy Weight & Light Weight


Heavyweight components are opaque, windows, drawn by native window system, not as portable. Lightweight components can have transparent backgrounds, drawn by JVM, portable. Swing classes extend AWTJava UI components can register listeners (or adapters) to react to events that are fired off by components. components have add*Listener() methods for expected events. listeners are java interfaces.

JFrame
Is a Top level containers are the root of a containment hierarchy. Interface between the native windowing environment and window manager and java application Contains a JRootPane which contains a contentPane container. components and layout managers must be added and set to the content pane JFrame

JFrame
JFrame displays components in an application windows, All Standalone GUI Application must extend Jframe. The content pane is got by the method getContentPane() Content Pane contains all the non-menu components displayed by the JFrame. Use JFrame's content pane to add components
frame.getContentPane().add(child);

All the methods should normally be sent to the content pane instead of the JFrame itself.

Example for JFrame


import javax.swing.*; public class FirstFrame extends JFrame { public static void main(String[] args) { JFrame frame = new FirstFrame(); JPanel panel1 = new JPanel(); JButton jb = new JButton("Press Me"); panel1.add(jb); frame.getContentPane().add(panel1); frame.setTitle("FirstFrame"); frame.setSize(300, 200); frame.show(); } }

actionPerformed()
The method that provides the functionality for the action. class MyAction extends AbstractAction { public MyAction(String text, Icon icon) { super(text,icon); } public void actionPerformed(ActionEvent e) { System.out.println("Action ["+e.getActionCommand()+"]!"); } }

Example
jb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { tbname.setText(" "); tpubcode.setText(" "); tprice.setText(" "); } }); }

Events

Events

Pane
LayeredPanes : Allow you to place JComponents on top of one another. The LayeredPane is further subdivided into five layers: default, palette, modal, popup and drag GlassPane (Component) A transparent canvas overlaying the contentPane. You use it typically for sprite animations. GlassPanes are also used to intercept mouse events for the frame. JRootPane: Deals with the decoration around the outside of the frame. DesktopPanes: A type of LayeredPane where the Jinternal Frames live, covering up the JFrame contents, free to move around anywhere inside the JFrame.

JPanel
Organizes a set of components as a group An Applet,Frame or dialog can contain several panels Panel can contain buttons,textfields,list etc., JPanel panel1 = new JPanel();

JApplet
Swing GUIs can be developed as applications extending applets extending JApplet Extend JApplet public void init() {...} The default layout manger for JApplet content pane is BorderLayout.

JComponent
Components are UI elements that are the members of containers and managed by layout managers it extends java.awt.Container controls: JButton, JTextField, JSlider displays: JLabel, JToolTip, JProgressBar Swing components are considered "lightweight.

They do not rely on objects within the operating system to render themselves. They draw themselves using the standard features of the abstract Graphics object, which not only decreases the amount of memory each component uses, but allows components to have transparent portions and take on nonrectangular shapes.

JLabel / JButton
JLabel(Hi There); JLabel(hi, JLabel.RIGHT); JLabel(new ImageIcon(icon.gif)); JLabel(An icon, new ImageIcon(icon.gif),JLabel.Center);

JButton b1 = new JButton(Button 1); b1.setMnemonic(1); // alt 1 b1.setEnabled(false); b1.addActionListener(this); ... public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { b1.setEnabled(true); b2.setEnabled(false); }...

Layouts

Components in a Java window distribute themselves to fill the available space. The exact manner of this distribution depends on what is called the window's layout, as defined by one of Java's layout manager classes. The layout manager classes with an illustration and overview of each.

Layouts

Layouts

Grid Layouts
A regular pattern of objects, such as a table of buttons, is easily displayed with a grid layout.

Layouts

Grid Bag Layouts


The grid bag layout is the most versatile and most complex layout manager.
It treats the display area as a grid of cells. The grid begins with no cells and adds cells as needed to accommodate the components. Components occupy rectangular blocks of cells called display areas. Cells can be empty, and their size can vary.

Layouts

a grid has been superimposed on the window. The button One occupies two cells. Each of the other buttons occupies a single cell. The remaining cells are empty.

Layouts

Layouts

Layouts

Layouts

Card Layouts
A card layout consists of a stack of components. Only one component can be seen at a time, but it is possible to switch between components. When a card layout is created, the top component is visible. Figure 22-13 illustrates a card layout.

Layouts

Panels
A panel is a container that can contain other components, including other panels. Fancy graphical user interfaces can be built by combining panels and other components in an imaginative manner.

JTabbedPane
A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon. Tabs are added to a TabbedPane object by using the addTab
public void addTab(String title, Icon icon, Component component, String tip) Adds a component and tip represented by a title and/or icon, either of which can be null. Parameters:
title - the title to be displayed in this tab icon - the icon to be displayed in this tab component - the component to be displayed when this tab is clicked tip - the tooltip to be displayed for this tab

JDialog extends Dialog


The JDialog component contains a JRootPane as its only child. The contentPane should be the parent of any children of the JDialog. Using JDialog : dialog.getContentPane().add(child); All the methods should normally be sent to the contentPane instead of to the JDialog. The default contentPane has a BorderLayout manager set on it. public JDialog(Frame owner, String title, boolean modal)

Class JOptionPane
JOptionPane pops up a standard dialog box that prompts users for a value or informs them of something. showConfirmDialog()
Asks a confirming question, like yes/no/cancel.

showInputDialog()
Prompt for some input.

showMessageDialog()
Tell the user about something that has happened.

showOptionDialog()
The Grand Unification of the above three.

JOptionPane
Show an error dialog that displays the message, 'alert':
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);

Show an internal information dialog with the message, 'information':


JOptionPane.showInternalMessageDialog(frame, "information","information", JOptionPane.INFORMATION_MESSAGE);

Show an information panel with the options yes/no and message 'choose one':
JOptionPane.showConfirmDialog(null,"choose one", "choose one", JOptionPane.YES_NO_OPTION);

Show an internal information dialog with the options yes/no/cancel and message 'please choose one' and title information:
JOptionPane.showInternalConfirmDialog(frame,"please choose one", "information",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);

JMenuBar
An implementation of a menu bar. Add JMenu objects to the menu bar to construct a menu.

Add JMenu objects to the menu bar to construct a menu.


When the user selects a JMenu object, its associated JPopupMenu is displayed, allowing the user to select one of the JMenuItems on it. JMenuItem: An implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the "button", the action associated with the menu item is performed.

Simple menu setup steps


1. 2. 3. 4. extend a JFrame for top container instantiate a JMenuBar instantiate a JMenu for every menu choice in the menu bar instantiate each JMenuItem, JRadioButtonMenuItem, or JCheckboxMenuItem choice in the JMenu 5. set JMenuItem icon 6. set mnemonics and/or key accelerators 7. add any submenus 8. add any item separators 9. add the JMenuItems to JMenu 10. add a common menuItemListener for all (set of) menu items 11. add an ActionListener each menu item. 12. add the JMenu to the JMenuBar 13. set the MenuBar in the frame

JScrollPane
Provides a scrollable view of a lightweight component. A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and optional row and column heading viewports. The JViewport provides a window, or "viewport" onto a data source - for example, a table . In addition to the scroll bars and viewport, a JScrollPane can have a column header and a row header.

JTable
The JTable is used to display and edit regular two-dimensional tables of cells.

JTable
public JTable(Vector rowData, Vector columnNames)
Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames. The Vectors contained in rowData should contain the values for that row.

MVC in Swing
Swings use of a simplified variant of the MVC design called the model-delegate This design combines the view and the controller object into a single element that draws the component to the screen and handles GUI events known as the UI delegate Swing component contains a model and a UI delegate. The model is responsible for maintaining information about the component's state. The UI delegate is responsible for maintaining information about how to draw the component on the screen. UI delegate (in conjunction with AWT) reacts to various events that propagate through the component.

Adding To The Frame


Need to get the content pane to add components to the frame frame.getContentPane().add(greenLabel, BorderLayout.CENTER); Adding a menu bar to the frame frame.setJMenuBar(greyMenuBar); Respond to window closing frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }) frame.pack(); // resolves all containment management frame.setVisible();

Вам также может понравиться