Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition.

Similar presentations


Presentation on theme: "Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition."— Presentation transcript:

1 Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition

2 What is Java Swing? Swing is a collection of classes and interface that define the Java GUI. It is built upon the foundation of the AWT. AWT(Abstract Window Toolkit) defines a basic set of controls, windows, and dialog boxes that support a usable, but limited GUI. It is Part of the Oracle’s Java Foundation Classes (JFC)- an API for providing a GUI for Java programs Offers a rich set of GUI components such as buttons, text fields, scroll bars, check boxes and so on…

3 Swing vs AWT AWT is Java’s original set of classes for building GUIs –Translates its visual components into their corresponding, platform specific equivalents, or peers –Not truly portable: looks different and lays out inconsistently on different OSs Due to OS’s underlying display management system Swing is designed to solve AWT’s problems –Lightweight components, entirely written in Java and do not rely on platform-specific peers Uses AWTs components –Window, frame, dialog –Lays out consistently on all OSs –Uses AWT event handling mechanism

4 Swing features  GUI components like button, checkbox, and so on…  Java 2D API: images, figures, animation  Pluggable look and feel(PLAF): use samples (metal, Windows and Motif) or create your own  Data Transfer: cut, copy, paste, drag & drop  Internationalization: supports different input language  Accessibility API: for people with disabilities  Undo Framework API: supports unlimited numbers of actions to undo and redo  Flexible Deployment: run within a browser as an applet or Java Application

5 Components and Containers A Swing GUI consists of components and containers A component is an object (an independent visual control)that represents an element on the screen –e.g. label, text area, text field A container is a component that holds other components –Can nest containers inside each other –e.g. windows, frames, dialogs, and panels

6 Components and Containers Swing defines two types of top-level containers: 1)Heavyweight containers: JFrame, JApplet, JWindow, and JDialog - do not inherit JComponent class but inherit AWT classes. 2) Lightweight containers: Jpanel, JRootPane - do inherit JComponent class In general, we create one or more components and add them to a container to display them on the screen –JFrame consists of multiple containers (panes)

7 JFrame - Each top-level container define a set of panes

8 8 The Initial Swing GUI Containment Hierarchy File Edit Undo Redo Cut Frame / Dialog / Applet Root Pane Layered Pane Content Pane Glass Pane a 3D model enables menus to pop up above the content pane allows for interception of mouse events and painting across GUI components

9  Root pane Created by Swing on realizing frame and‘Invisibly’ attached to top-level container (e.g. JFrame) The root pane manages the other panes and the (optional) menu bar. The panes that comprise the root pane are glass pane, the content pane, and the layered pane.  Glass pane It is the top level pane. It sits above and completely covers all other panes By default, it is a transparent instance of Jpanel It enables you to manage mouse events that affect the entire container  Layered pane Provided by root pane, It is an instance of JLayeredPane. The layered pane allows components to be given a depth value. It holds the content pane and the (optional) menu bar.  Content pane It is an instance of JPanel This is the pane to which you will add visual components

10 GUI Program Design The GUI provides a view of the program, it is clearly not the program Making the GUI code as independent of the program code is a good strategy –Changes in the program do not necessarily change the GUI –Different GUIs can be developed for the same program –Debugging and maintaining both the GUI and the program code is easier

11 Model-View-Controller(MVC) Design pattern often used in Swing Breaks a GUI component down into three parts –“Model” corresponds to the state information associated with a component –“View” determines how the component looks when rendered on the screen –“Controller” interprets user input, commanding the model and view to change as necessary

12 MVC ModelView Controller The model passes its data to the view for rendering The view determines which events Are passed to the controller The controller updates the model Based on the events received

13 MVC in Swing Swing often merges the View and Controller together into one object called the UI delegate. The UI delegate interprets the user’s interactions and updates the model. It also handles the display. Swing’s approach is called the Model-Delegate architecture. Because the view(look) and controller(feel) are separate from the model, the look and feel can be changed without affecting how the component is used within a program.(PLAF)

14 MVC in Swing Model View Controller Delegate Program Logic The Application

15 The MVC Power One of the best examples of MVC/Delegates in Swing is the pluggable look and feel (PLAF) PLAF enables the entire UI look to be changed by simply switching PLAF’s A simple matter of switching the delegate which draws buttons, lists, etc. Replaces AWT’s heavyweight OS-look with a controllable, lightweight one.

16 Building a GUI A GUI is built in layers. Bottom most layer is the window ( Container ) - usually a JFrame (for an application), or a JApplet –Contains all other components –Can provide basic features like maximise/minimise buttons, title bar, menu bar, etc On top of this, components are layered ( Component ) –Components, e.g. buttons, text fields –or intermediate containers, e.g. panels Arrangement of components in a container is handled by a layout manager –Its job is to instruct components on how to arrange themselves so the GUI is drawn correctly. Write some Listeners and attach them to your Components Interacting with a Component causes an Event to occur A Listener gets a message when an interesting event occurs, and executes some code to deal with it Display your window

17 Steps to build a GUI There are 5 steps to creating a Java based GUI: 1.import the GUI packages 2.declare the widgets to be used in the GUI 3.add the widgets to a container 4.implement any event handling 5.show the GUI

18 Build from bottom up Create: Frame Panel Components Listeners Add: (bottom up) listeners into components components into panel panel into frame JPanel JButton Listener JFrame JLabel

19 Using a GUI Component 1.Create it Instantiate object: b = new JButton(“press me”); 2.Configure it Properties: b.text = “press me”; [avoided in java] Methods: b.setText(“press me”); 3.Add it panel.add(b); 4.Listen to it Events: Listeners JButton

20 A Simple Framed Window import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); frame.setVisible(true); }

21 Notes on the Example setSize and setLocation require java.awt.* ; the rest require javax.swing.* The JFrame constructor argument is used as a title The Dimension constructor takes an integer width and height, respectively The setLocation method takes a pair of integer coordinates (x,y) where (0,0) is the upper left corner of the display The visibility of a JFrame is set to false by default

22 Changing Background Color import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); Container contentPane = frame.getContentPane(); contentPane.setBackground(Color.red); frame.setVisible(true); }

23 Content Panes Q: Why not just: frame.setBackground(Color.red); ? Ans: In order to be lightweight, Swing's top-level window objects must be built on top of a lightweight AWT Container object introduced in version 1.1 This container is called a content pane

24 24 Swing Hello World import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World!"); frame.setSize(220, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(null); JButton button = new JButton("Hello World!"); button.setLocation(30, 30); button.setSize(150, 100); contentPane.add(button); frame.setVisible(true); }

25 JFrames A JFrame is a Window with a title and a border A JFrame provides the basic building block for screen- oriented applications. JFrame win = new JFrame( “title” );

26 Creating a JFrame import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setVisible(true); //win.show(); } } // SwingFrame

27 Creating a JFrame import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setSize( 250, 150 ); win.setVisible(true); //win.show(); } } // SwingFrame

28 JLabels Jlabel is a component that you can put text into. When creating a label you can specify the initial value and the alignment you wish to use within the label. lbl = new JLabel( ”text", JLabel.RIGHT ) ;

29 Hello World import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel( "Hello World" ); win.getContentPane().add( label ); win.pack(); // set frame size win.setVisible(true); //win.show(); } } // SwingFrame

30 JButtons JButton extends Component, displays a string and delivers an ActionEvent for each mouse click. Normally buttons are displayed with a border In addition to text, JButtons can also display icons button = new JButton( ”text“ ) ;

31 Buttons import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); JButton button = new JButton( "Click Me!!" ); win.getContentPane().add( button ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

32 Layout Manager –An interface that defines methods for positioning and sizing objects within a container. Java defines several default implementations of LayoutManager. Layouts allow you to format components on the screen in a platform independent way The standard JDK provides five classes that implement the LayoutManager interface: –FlowLayout –GridLayout –BorderLayout –CardLayout –GridBagLayout Layout managers are defined in the AWT package

33 Changing the Layout To change the layout used in a container you first need to create the layout. Then the setLayout() method is invoked on the container is used to use the new layout. The layout manager should be established before any components are added to the container JPanel p = new JPanel() ; p.setLayout( new FlowLayout() );

34 Layout Manager Heuristics Left to right, Top to bottom c n s ew FlowLayoutGridLayout BorderLayout none, programmer sets x,y,w,h null One at a time CardLayout GridBagLayout JButton

35 Code: null layout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null);// x,y layout p.add(b); f.setContentPane(p); press me

36 Code: FlowLayout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); FlowLayout L = new FlowLayout( ); JButton b1 = new JButton(“press me”); JButton b2 = new JButton(“then me”); p.setLayout(L); p.add(b1); p.add(b2); f.setContentPane(p); press methen me

37 FlowLayout When you add components to the screen, they flow left to right (centered) based on the order added and the width of the screen. If the screen is resized, the components' flow will change based on the new width and height

38 Flow Layout import javax.swing.*; import java.awt.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.getContentPane().setLayout( new FlowLayout() ); for ( int i = 0; i < 10; i++ ) win.getContentPane().add( new JButton( String.valueOf( i ) ) ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

39 FlowLayout

40 GridLayout Arranges components in rows and columns –If the number of rows is specified columns = number of components / rows –If the number of columns is specified Rows = number of components / columns –The number of columns is ignored unless the number of rows is zero. The order in which you add components matters –Component 1  (0,0), Component 2  (0,1), …... Components are resized to fit the row-column area

41 GridLayout gridLayout( 2, 4 ) gridLayout( 0, 4 ) gridLayout( 4, 4 )gridLayout( 10, 10 )

42 BorderLayout BorderLayout provides 5 areas to hold components. These are named after the four different borders of the screen, North, South, East, West, and Center. When a Component is added to the layout, you must specify which area to place it in. The order in which components is not important. The center area will always be resized to be as large as possible

43 BorderLayout import javax.swing.*; import java.awt.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); Container content = win.getContentPane(); content.setLayout( new BorderLayout() ); content.add( "North", new JButton( "North" ) ); content.add( "South", new JButton( "South" ) ); content.add( "East", new JButton( "East" ) ); content.add( "West", new JButton( "West" ) ); content.add( "South", new JButton( "South" ) ); content.add( "Center", new JButton( "Center" ) ); win.pack(); win.setVisible(true); //win.show(); } } // SwingFrame

44 BorderLayout

45 Default Layout Managers The default layout manager for content panes is BorderLayout. Recall that the following Swing components have content panes: –JWindow –JFrame –JDialog –JApplet –JInternalFrame The other Swing container is the JPanel, whose default layout manager is FlowLayout.

46 Event Handling The Delegation Event Model: Provides a standard mechanism for a source to generate an event and send it to a set of listeners. In the delegation event model, there are three participants: 1.Event: It is an object that describes a state change in a source. –Each time a user interacts with a component an event is generated, e.g.: A button is pressed A menu item is selected A window is resized A key is pressed –An event informs the program about the action that must be performed 2.Event source : It is an object whose state changes. It generates Events. 3.Event listener: It is an object that is notified when an event occurs.

47 A listener receives event notifications A listener must: –Register with one or more sources for a specific type of event –Implement an interface to receive those events –Unregister if those events are not needed any longer Source Listener events container The Delegation Event Model Event Handling

48 Handling: –create a component e.g., a JButton –add it to the GUI e.g., to a JPanel –register a listener to be notified when the component generates an event e.g., interface ActionListener –define the callback method e.g., actionPerformed()

49 How to Implement an Event Handler Every event handler requires three pieces of code: 1.declaration of the event handler class that implements a listener interface or extends a class that implements a listener interface public class MyClass implements ActionListener { 2.registration of an instance of the event handler class as a listener someComponent.addActionListener(instanceOfMyClass ); 3.providing code that implements the methods in the listener interface in the event handler class public void actionPerformed(ActionEvent e) {...//code that reacts to the action... }

50 A Simpler Event Example public class ButtonClickExample extends JFrame implements ActionListener { JButton b = new JButton("Click me!"); public ButtonClickExample() { b.addActionListener(this); getContentPane().add(b); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { b.setBackground(Color.CYAN); } public static void main(String[] args) { new ButtonClickExample(); } 1 2 3

51 Event Example public class SwingApplication extends JFrame { private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; JLabel label = new JLabel(labelPrefix + "0 "); public SwingApplication(String title) { super(title); JButton button = new JButton("I'm a Swing button!"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { label.setText(labelPrefix + ++numClicks); } }); JPanel panel = new JPanel(); panel.add(button); panel.add(label); getContentPane().add(panel); pack(); setVisible(true); } public static void main(String[] args) { new SwingApplication("SwingApplication"); }}

52 Event Handling Options for implementing listeners: –anonymous inner classes –named inner classes –listener class


Download ppt "Java Swing Reference: 1.Swing: A Beginner’s Guide by Herbt Schildt, TMH Edition."

Similar presentations


Ads by Google