Академический Документы
Профессиональный Документы
Культура Документы
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
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;
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.
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.
Nested Classes
class MyOuter { public static class MyInner { //... public void function1() {} //more function (static and more) } }
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
The only modifiers you can apply to a method-local inner class are abstract and final.
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
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
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),
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.
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
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)
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.
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
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
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 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.
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.