Presentation on theme: "Introduction to Java 2 Programming"— Presentation transcript:
1Introduction to Java 2 Programming Lecture 8Java Swing API, Part 1
2Overview Java AWT/Swing Fundamentals of Swing (Part 1, this lesson) Brief history, introduction to the main packagesFundamentals of Swing (Part 1, this lesson)ContainersComponentsLayoutsFundamental of Swing (Part 2, next lesson)Event-driven programmingApplets (Part 3, last lesson)Writing, and deploying applets
3Java AWT Abstract Windowing Toolkit Original Java GUI API Very limited in capabilityFew componentsAPI not well structured, particularly event handling for user actionsNot entirely portable (used native widgets)The AWT was the original Java GUI API, and for a long time was the only way of building GUI applications. It’s built as a series of wrappers around native code specific to the underlying operatin system. E.g. on Window it uses the windows API internally, varies by platform.However it is very limited (few components), very poor in comparison to native toolkits, not entirely portable. API isn’t very well designed, particularly the event handling (which deals with tying user activities – e.g. pressing a button – to appliation logic).These limitations may be partly to blame for the limited penetration of Java on the desktop, and even applets beyond its initial hype: AWT is clunky.It was therefore replaced…
4JFC/Swing Java Foundation Classes (or “Swing”) Replacement for AWT (although does share some classes)Also provide basis for developing new GUI features (which are being continually added)What does Swing include?100% JavaSwing components (more, and more sophisticated)Pluggable Look and Feel SupportAccessibility APIBetter graphics support (Java 2D)Drag and DropThe JFC (or “Swing”) was added as an extension for Java 1.1, but was properly included in Java 1.2 and upwards. Swing was the project code name.The majority of Swing is implemented in pure Java making it highly portable, although it can be resource intensive. Some features (e.g. D’n’D) involve some native code.Includes many more components (we’ll see these later); pluggable look-and-feel (makes applications look more like their native counterparts), improved graphics, etc.
5JFC/Swing Disadvantages Can be slow (resource hungry)Large complex API (big learning curve)Many features best suited for GUI builders, IDEsAim of the next few lectures is to introduce the basic conceptsProvide you with background so can continue studies yourselfImportant to use Swing and not AWTSwing is the recommended way to build Java GUIsDisadvantages include it can be sluggish, very complex, so can have a big learning curve. Some features are best explored (or hidden!) behind a decent IDE that supports GUI building. Borland Jbuilder, which is available free for personal use is a good editor.Aim of this and the remaining lectures is to introduce the basics of Swing, the basic concepts to provide with enough background to further explore the API. It’s a very OO API, so its useful to get some exposure to it as an example of a good OO framework. The Event-Handling concept is also a useful one to understand and used in many applications.It IS possible to build GUIs with AWT, but its not recommended, so I’d be doing you all a diservice if I only cover that in this course.
6Introduction to GUI Programming What are the stages in building a GUI application?Design the user interfaceOrganising pre-built GUI components to build windows, dialogsE.g buttons, tables, menus, etcWriting the application logicWhat does the application do?Writing event-handling code to tie the GUI components to the application logicMore on event-handling in next lesson…One way to build a GUI application is to design the UI, perhaps using a GUI building tool to construct the initial design, deciding which components to use, and how they’re laid out. E.g. do we display data as a table, or a series of text fields? How do we let the user make selections, from a list, radio buttons, check boxes, etc.We might then progress to writing the application logic – the meat of the application.The remaining steps are to tie together the GUI with the application logic, so the application responds appropriately to the users activities.
7Introduction to GUI Programming Essentially, JFC/Swing provides a framework which consists of:A number of GUI components that can be used to build a user interface (javax.swing)An event-handling framework for tying user actions to application code (javax.swing.event)Occasionally use classes from the AWT equivalents (java.awt, java.awt.event)Some Swing classes inherit from originalsDistinguish Swing versions from AWT versions with “J” prefix.We’ll cover the first part of this in this lecture, and progress to event handling next time.Two basic packages, although there are a number of others. AWT hasn’t entirely gone away – basically it wasn’t ALL bad. Some Swing classes inherit from the AWT originals, but implemented completely differently. Swing classes are often termed “lightweight” because they have no native portion, conversely AWT classes are “heavyweight”.To make naming obvious, the Swing versions of classes originally in AWT include a “J” prefix. E.g. Button/Jbutton, Frame/Jframe.
8Building a GUI A GUI is built in layers. Bottom most layer is the window (Container)Contains all other componentsCan provide basic features like maximise/minimise buttons, title bar, menu bar, etcOn top of this are layered (Component)Components, e.g. buttons, text fieldsor intermediate containers, e.g. panelsArrangement of components in a contained is handled by a layout managerIts job is to instruct components on how to arrange themselves so the GUI is drawn correctly.Top level containers, intermediate containers, components.This is all pretty standard stuff, very similar principle in Visual Basic and other GUI development environments.One quirk about Java is that the layout of components on a window (or form in VB parlance) is handled by a component called a layout manager. When drawing a GUI window, the components negotiate with their layout manager with how much space they need, positioning, etc. So the layout manager is ultimately responsible for arranging the components.Unlike in VB which uses absolute positioning: where you put the control is where it’ll always be. In java resizing a window can completely ruin a display, unless you’ve very carefully configured the layout manager. This is the point where you need a GUI builder. Personally I find it the most frustrating part of Swing. However, with care, you CAN build simple GUI apps by hand.
9Building a GUI X Simple Application OK A Label Cancel Text field… Simple animation showing how a simple application window is constructed by layering components on top of one another. First we add some buttons, then a panel to further group components, then finally a text label and a text entry field.CancelText field…
10The containment hierarchy This layered GUI can be viewed as a hierarchy of componentsNOT an inheritance hierarchy,It just describes how components are nested one within another
11The containment hierarchy JFrameJButtonJButtonJPanelStress that this isn’t showing inheritance, its show which components are nested inside which other components.JLabelJTextField
12Swing Top level containers JWindowBasic no frills window, just a square on the screenJFrameThe basic Swing window. Offers basic window controls, resizableJDialogFor building dialog boxes, e.g. File open/saveJAppletFor building applets, embedded into a web pageReferred to a containers, because in at least one case there’s not actually a window (applets are embedded in a web page).Jframe and Jdialog are most commonly used. Several built in dialog types mimicking those built in to many apps (e.g. File Open, File Save, Choosing Colors from a Palette, etc).Show demos at this point of a window, frame, and dialog.
13Working with JFramesMany different possibilities, but the basics include:Setting window titleSetting location on screenSetting size of windowRestricting resizesSet close operation (exit the program), as by default it does nothing.Introduce the basics of working with Jframes. Show example code here.
15Adding Components to a Frame A JFrame has several areasWindow decorations(Optional) Menu barContent paneContent pane is where components are added.Content pane is a Container objectObtain reference to the content pane, and then add another component to itJFrame frame = new JFrame(“Example”);JButton button = new JButton(“Click me!”);frame.getContentPane().add( button );Content pane is where all the components live. When you’re using a frame object you need to invoke the getContentPane method to get a reference to the object, and then add things to it.
16Adding Components to a Frame JFrameAndButton.javaJFrameAndPanel.java
17Adding ComponentsVery common to extend the Swing components, particularly JFrameCreate your own specialised versionsMay include a fixed set of componentsProvide extra methods for working with those components, etc.Encapsulates how the GUI is constructedSlightly different to Visual Basic where one tends to just use the basic components
18Layout ManagersResponsible for layout out (arranging) components in a ContainerSeveral different types with different usesNone of them provide for precise x-y alignment, unlike VB forms
19Border Layout This is the default layout for JFrame Divides the content pane into 5 areas (north, south, east, west, center)Areas are expanded/contracted as needed, along with their contents.Therefore ignores preferred size of the components.Center is the default if not specified.Adding two components to the same zone means they get added one on top of the otherInstead add the components to a JPanel, and then add that instead.
20Border Layout X NORTH WEST CENTER EAST SOUTH Simple animation showing how a simple application window is constructed by layering components on top of one another. First we add some buttons, then a panel to further group components, then finally a text label and a text entry field.SOUTH
21Grid Layout Divides the container into a rectangular grid Configurable number rows/columnsEach grid location is of equal size, one component assigned to each.Automatically assigns components to next available location
22Other layout managers Flow Layout (default for JPanel) Card Layout Arranges components left-to-rightUsed to arrange buttons on a panelCard LayoutArranges components like a deck of cardsOnly one card visible at a timeBox Layout, Grid Bag LayoutVery sophisticated managers, used by GUI builders for very precise GUI designs.Not recommended for hand use!
23Menus A Jframe can have only a single menu bar Instance of the Jmenu objectA menu bar can have several menus on itInstances of the Jmenu objectA menu can have several items on itInstances of the JmenuItem objectExample