Java swing 1

  • 509 views
Uploaded on

java swing

java swing

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
509
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
87
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Java Swing Basics - 1 Java Swing Basics What is a user interface? User interface is that part of a program that interacts with the user of the program. UI can be a simple command-line interface to the point-and-click graphical user interfaces provided by many modern Windows-based applications. What is the Abstract Window Toolkit (AWT)? (1) The AWT contains many classes and methods that allow the programmer to build an application’s user interface. These classes are contained in a package called the java.awt. It is one of the java’s largest packages. (2) The basic idea behind the AWT is that a java window is a set of nested components starting from the outermost window all the way down to the smallest User Interface component. (3) AWT can be used to create applets or GUI-based applications, handle events, draw text and graphics. (4) The AWT provides a machine-independent interface for applications. What is Java API? The three main components of Java are: (1) The Java language – it defines the syntax and semantics of the Java programming language. E.g., it defines the syntax of if/then statements, primitive data types such as int, double, the syntax of class declaration, etc (2) The Java Virtual Machine (JVM) – It executes the Java bytecode. (3) The Java API (Application Programming Interface) – An API is a library of functions that is provided in a language for common tasks such as networking, graphics, file transfer and creating complex data structures. An API provides interaction between different software programs just as a user interface provides an interaction between human being and a computer. It is a set of classes included with the Java Development Environment. These classes run on the JVM. These classes include the GUI classes as well. Thus, AWT is an API and it is contained in the package called java.awt. Explain the terms “Component” and “container” with reference to Java AWT The AWT defines windows components according to a class hierarchy. In this hierarchy, there is an additional functionality in a class at each level. The two most windows are those derived from the Panel class and the Frame class. Component Class: (1) At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. (2) All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. (3) It defines many public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window. (4) A Component object is responsible for remembering the current foreground and background colors and the currently selected text font. (5) Components talk to each other via events. Prof. Mukesh N. Tekwani Page 1 of 42
  • 2. Java Swing Basics - 1 (6) Objects of the Component class are GUI controls. They can be displayed on the screen and user can interact with them. (7) All components have the following common properties: a. They have a screen position and a size. b. They can be enabled or disabled. c. They have a standard interface to handle events. d. Foreground and background color can be assigned. (8) Components defined in the AWT package are called “heavy-weight” components since they require the support of native graphics libraries. But Swing components are light-weight. Container Class: (1) The Container class is a subclass of Component. It is an abstract class. (2) It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container. (3) A container is responsible for laying out any components that it contains. It does this through the use of various layout managers. (4) The fundamental container components are: Frame, Window, Applet, and Panel. Window Class: (1) The Window class creates a top-level window. (2) We can add components such as buttons, labels, etc to windows. These components are added with the help of Layout managers. (3) The top-level window is not contained within any other object. It sits directly on the desktop. (4) Generally we don’t create Windows objects directly but instead use a sub class of Windows called Frame. (5) Window has 2 sub-classes: Frame and Dialog. What is Java Foundation Class (JFC)? (1) Java Foundation Classes are a part of the Java language. JFC is a collection of APIs which allows developers to create complete applications. It includes 5 APIS: AWT, Swing, Drag and Drop, Java 2D, and Accessibility. (2) JFC are a set of GUI components which simplify the development and deployment of applications. JFC is a superset that contains AWT. (3) Applications built using JFC are not locked into a specific look and feel. Using JFC, developers can create apps that either have a native platform look and feel or use the Java look and feel -- or they can create their own custom look and feel. What are the disadvantages/drawbacks/limitations of AWT? 1. The AWT provides a basic set of controls, windows and dialog boxes that support a limited graphical interface. 2. The reason for this limitation is that AWT translates its various visual components into their corresponding platform-dependent equivalents (also called peers). 3. Therefore the look-and-feel of a component is decided by the platform(hardware and software) and not by Java. 4. AWT components use the native code and are called “heavy weight components”. 5. This use of native code peers results in the following problems: a. A component might look and act differently on different platforms. This cannot be permitted because the philosophy of Java is write-once, run anywhere. b. The look-and-feel of each component was fixed because it was decided by the platform and could not be changed. mukeshtekwani@hotmail.com Page 2 of 42
  • 3. Java Swing Basics - 1 c. These AWT components have restrictions such as all these components are rectangular and opaque. What is Swing? OR What are the main features of Swing? (1) Swing is a set of classes that provide more powerful and flexible components than are possible with the AWT. (2) In addition to the components such as buttons, check boxes, and labels, Swing supplies several new components such as tabbed panes, scroll panes, trees, and tables. (3) A button may have both an image and a text string associated with it. The image can be changed as the state of the button changes. We can add or change the borders drawn around the Swing component. (4) Swing does not eliminate AWT, but it is based on the foundations of AWT. Swing also uses the same event handling mechanism as the AWT and hence AWT is an essential part of Java. (5) Swing provides “lightweight” components. It means they are written entirely in Java and are not specific to any platform. (6) These lightweight components are rendered using graphics primitives (such as a point, line or an arc). Hence these components can be transparent and non rectangular in shape. (7) Since these lightweight components do not translate into native peers, the look-and-feel of each component is determined by Swing and not by the underlying architecture or OS. Hence all components work in a consistent manner across all platforms. (8) Swing supports a pluggable look and feel (PLAF). a. Since each component is rendered by Java code and not by native peers, the look and feel of each component is under the control of Swing. b. Thus, it is possible to separate the look and feel of a component from the logic of the component. Thus, we can change the way a component looks without changing any of its other aspects like behavior. c. We can “plug in” a new look and feel for any component without creating any side effects in the code that uses that component. d. We can define an entire set of look-and-feels that represent different GUIS (similar to the concept of themes). To use a specific style, its look and feel is simply “plugged in” and all components are automatically rendered using that style. e. Java provides the so-called “metal look and feel” which is the default. What are the advantages of Swing over AWT? (1) Although Swing overcomes many limitations of AWT, Swing is not a replacement for AWT. (2) The biggest advantage (difference) Swing and AWT is that the Swing components are implemented with absolutely no native code. Native code is the code that is compiled to run on a particular processor only. (3) AWT components are restricted to features that are available on every platform. But Swing components aren't restricted to the features that are present on every platform and so they can have more functionality than AWT components. (4) AWT provides a basic set of controls, windows, and dialog boxes that support a limited graphical interface. The reason for this limitation of AWT is that it translates the various visual components into their corresponding, platform dependent equivalents or peers. It means that the look and feel of a component is defined by the platform, not by Java. Because the AWT components use native code, they are called “heavy weight”. Swing components are not implemented by platform-specific code but are implemented in Java. The term “lightweight” is used to describe such elements. (5) The Swing related classes are contained in javax.swing package and its sub packages. Prof. Mukesh N. Tekwani Page 3 of 42
  • 4. Java Swing Basics - 1 Write a note on the MVC Architecture A visual component has three different aspects. These are: 1. The way the component looks when rendered on the screen (View) 2. The way the component reacts to the user (control) 3. The state information associated with the component. (Model) The Model-View-Controller (MVC) component is used implement a component. In the MVC architecture, 1) The Model corresponds to the state information associated with the component. For example, consider a check box. The model contains a field that indicates whether the box is checked or unchecked. 2) The View determines how the component is displayed on the screen. The current state of the model may affect the view. 3) The Controller determines how the component reacts to the user. E.g., when the user clicks a check box, the controller reacts by changing the model to reflect the user’s choice (checked or unchecked). This affects the view which is then updated. 4) By separating a component into a model, a view and a controller, the implementation of each part can be changed without affecting the other two aspects of the component. Model-Delegate Architecture: 1) Swing uses a modified form of MVC that combines the view and the controller into a single logical entity called the UI delegate. (V + C = Delegate). Hence the architecture used in Swing is called as the Model-Delegate architecture or the Separable Architecture. 2) The pluggable look-and-feel of Swing components is possible due to the Model-Delegate architecture. 3) Since the view (look) and the controller are separate from the model, the look and feel can be changed without affecting how the component is used with the program. 4) We can also change the model without affecting how the component appears on the screen or how it interacts with the user. 5) In order to support the Model-Delegate architecture, Swing components contain two objects. The first object represents the model. The second object represents the UI Delegate. Models are defined by interfaces. (Using an interface we can specify what a class can do but not how it does it. Interfaces are declared like classes but they do not have instance variables and their methods do not have a body) Explain the terms “Component” and “container” with reference to Java Swing. Basics: 1) A Swing GUI consists of two items: components and containers. 2) A component is an independent visual control such as a command button, or a slider. 3) A container holds a group of components. Thus, a container is a special type of component that is designed to hold other components. 4) A component must be placed inside a container so that it can be displayed. Hence all Swing GUIs will have atleast one container. 5) Since a container is a component, a container can also hold other containers. Hence Swing has a concept of containment hierarchy. Components: 1) Swing components are derived from the JComponent class. 2) JComponent class provides the functionality that is common to all the components. 3) JComponent class supports the pluggable look and feel. 4) JComponent class inherits the AWT classes Container and Component. Page 4 of 42 mukeshtekwani@hotmail.com
  • 5. Java Swing Basics - 1 5) All of Swing’s components are represented by classes defined with the package javax.swing. Some of the class names for Swing components are (all these begin with the letter J): JApplet, JButton, JCheckBox, JComboBox, JList, JScrollBar, JMenu, JPasswordField, JToolBar, JWindow, JTree, JLabel. Containers: 1) There are two types of containers in Swing – the top-level containers: JFrame, JApplet, JWindow, and JDialog. These top-level containers are heavyweight. 2) These containers donot inherit the JComponent class. But they inherit the AWT classes Component and Container. 3) A top level container is at the top of the containment hierarchy. A top level container is not contained within any other container. 4) Swing also supports the lightweight containers. E.g., JPanel. Lightweight containers are used to organize groups of related components. Creating a Frame 1. A top-level window (that is, a window that is not contained inside another window) is called a frame in Java. 2. Swing has a class called JFrame; JFrame extends the Frame class of AWT. 3. Frames are examples of containers. This means that a frame can contain other user interface components such as buttons and text fields. 4. Frame is mostly used instead of window because it gives additional facilities such as menu bar, moving the window, and resizing it. 5. Frames can have titles and the constructor Frame() is used to set this title as follows: Frame f = new Frame(“Swing Frame”); 6. We can add components to the Frame with the help of add() method. 7. When a frame window is created it is invisible; we have to use the show() method to display the frame. Program 1: Program to display an empty frame on the screen import javax.swing.*; class SimpleFrame extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; public SimpleFrame() { setSize(WIDTH, HEIGHT); } } public class SimpleFrameTest { public static void main(String[] args) { SimpleFrame frame = new SimpleFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } Prof. Mukesh N. Tekwani Page 5 of 42
  • 6. Java Swing Basics - 1 Program Analysis: (1) The Swing classes are placed in the javax.swing package. (2) By default, a frame has a rather useless size of 0 × 0 pixels. We define a subclass SimpleFrame whose constructor sets the size to 300 × 200 pixels. (3) In the main method of the SimpleFrameTest class, we start out by constructing a SimpleFrame object. (4) Next, we define what should happen when the user closes this frame. For this particular program, we want the program to exit. To select this behavior, use the statement frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); (5) Simply constructing a frame does not automatically display it. To show the frame, the main method calls the setVisible() method of the frame. (6) Afterwards, the main method exits. Note that exiting main does not terminate the program, just the main thread. Showing the frame activates a user interface thread that keeps the program alive. (7) In this program, we wrote two classes: one to define a frame class and the other contains a main() method that creates and shows the frame object. Program 2: Program to display a frame with two images Write a Swing application that displays two command buttons on a JFrame. The buttons should display an image as well as text. //Swing program to display a frame with 2 images import javax.swing.*; import java.awt.*; class P4 extends JFrame { public P4() //constructor { JFrame jfrm = new JFrame("Displaying 2 images"); jfrm.setSize(300, 100); jfrm.setLayout(new FlowLayout()); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon img1 = new ImageIcon("twitter.png"); ImageIcon img2 = new ImageIcon("google.png"); JButton b1 = new JButton("Twitter", img1); JButton b2 = new JButton("Google", img2); jfrm.add(b1); jfrm.add(b2); jfrm.setVisible(true); } Page 6 of 42 mukeshtekwani@hotmail.com
  • 7. Java Swing Basics - 1 public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { new P4(); } }); } } Here is the output of the above code: In the above program we have used ImageIcon img1 = new ImageIcon("twitter.png"); ImageIcon is a Swing class; it encapsulates an image. The constructors of ImageIcon help to fetch the image from a file or URL. JWindow (1) A JWindow is a top-level container. (2) It can be displayed anywhere on the desktop. (3) JWindow does not have a title bar, and window-management buttons. (4) The user cannot move or resize the window. (5) It has no border. (6) The default layout for JWindow is BorderLayout. Program 3: Program to implement the JWindow class and display 2 buttons & a label. //Swing program to illustrate the JWindow import javax.swing.*; import java.awt.*; class JWindowDemo extends JWindow { public JWindowDemo() //constructor { JWindow jwin = new JWindow(); jwin.setSize(200, 100); JButton b1 = new JButton("ARTS"); Prof. Mukesh N. Tekwani Page 7 of 42
  • 8. Java Swing Basics - 1 JButton b2 = new JButton("SCIENCE"); JLabel lbl1 = new JLabel("COMMERCE"); jwin.setLayout(new BorderLayout()); jwin.add(b1, BorderLayout.EAST); jwin.add(lbl1, BorderLayout.WEST); jwin.add(b2, BorderLayout.CENTER); jwin.setVisible(true); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { new JWindowDemo(); } }); } } JLabel 1. This component creates a label that can be used to display fixed text and / or an icon. 2. This component is passive – i.e. it does not respond to the user input such as mouse click. 3. The JLabel has a transparent background. 4. JLabel has many constructors such as : a. JLabel (Icon, icon) b. JLabel (String str) c. JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text / icon within the dimensions of the label. Permitted values of align are: LEFT, RIGHT, CENTER. These constants are defined in the SwingConstants interface. Here, icons are specified by an object of type Icon which is an interface defined by Swing. To use an Icon, we use the ImageIcon class. ImageIcon implements Icon interface and encapsulates and image. So we pass an object of type ImageIcon as an argument to the Icon parameter of JLabel’s constructor. [An instance is similar to a class except that it does not have instance variables and the methods do not have a body] To obtain the icon and string associated with the label: Icon getIcon() String getText() Page 8 of 42 mukeshtekwani@hotmail.com
  • 9. Java Swing Basics - 1 To set the icon and text associated with a label: yoid setIcon(Icon icon) void setText(String str) Example of creating an icon and a label // Create an icon ImageIcon ii = new ImageIcon("france.gif"); // Create a label JLabel jl = new JLabel("France", ii, JLabel.CENTER); Methods provided by JLabel class: Method void setText(String) String getText() void setDisplayedKeyAccelerator(char) char getDisplayedKeyAccelerator() void setIcon(Icon) Icon getIcon() void setHorizontalAlignment(int); void setVerticalAlignment(int); void getHorizontalAlignment(int); void getVerticalAlignment(int); Description Defines a single line of text that will be displayed on the label. Returns the text string that is displayed on the label The set method specifies a character that indicates the shortcut key. It returns the character that is used as shortcut key. It sets an icon to the label It returns an icon associated with the image. It specifies where in the label its contents should be displayed Returns the position of the label contents. Program 4: Program to illustrate the use of a JLabel component: Compiling the program: C:>javac SwingDemo.java This creates the class file called SwingDemo.class, if there are no errors. To run this program: C:>java SwingDemo // A simple Swing application. import javax.swing.*; class SwingDemo { SwingDemo() { // Create a new JFrame container. JFrame jfrm = new JFrame("A Simple Swing Application"); // Give the frame an initial size. Prof. Mukesh N. Tekwani Page 9 of 42
  • 10. Java Swing Basics - 1 jfrm.setSize(275, 100); //Terminate program when user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a text-based label. JLabel jlab = new JLabel("Swing creates powerful GUIs.", JLabel.CENTER); // Add the label to the content pane. jfrm.add(jlab); } // Display the frame. jfrm.setVisible(true); } // end of constructor method public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new SwingDemo(); } } ); } // end of p.s.v.m method //end of class SwingDemo We now explain each of these statements in detail: import javax.swing.*; This package contains the components and methods defined by Swing. This package defines the classes that implement labels, buttons, text controls, and menus. This statement is included in all programs that use Swing. class SwingDemo We declare the SwingDemo class. SwingDemo() We add a constructor method for the class. // Create a new JFrame container. JFrame jfrm = new JFrame("A Simple Swing Application"); We create a JFrame using the above code. This creates a container called jfrm. This defines a rectangular window which has a title bar, close, minimize, maximize and restorer buttons and a system menu. This is a top-level window. The title of the window is passed to the constructor. [A frame is a top level container. It provides a place for other Swing components.] // Give the frame an initial size. jfrm.setSize(500, 500); Page 10 of 42 mukeshtekwani@hotmail.com
  • 11. Java Swing Basics - 1 We set the size of the window by using the setSize method. The dimensions are in pixels. The first value is the width and next value is the height of the window. // Terminate the program when user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Here we are stating what should happen when the user closes the window. When the top-level window is closed, we want the entire application to close. This is achieved by using the above statement. // Create a text-based label. JLabel jlab = new JLabel("Swing creates powerful GUIs.", JLabel.CENTER); We now create a Swing JLabel component. A JLabel component doesnot accept any user input; it simply displays a text, an icon, or both. We pass the text to be displayed and the alignment constant to the constructor. [A label is also called an atomic component; it cannot hold other components.] // Add the label to the content pane. jfrm.add(jlab); We add the label to the content pane of the frame. All top-level containers have a content pane in which components are stored. So to add a component to a frame we must add it to the frame’s content pane. This is done by calling the add() method. // Display the frame. jfrm.setVisible(true); This statement causes the window to become visible. If the argument of setVisible() method is true, the window will be displayed. By default, a JFrame is invisible, so setVisible(true) must be called to show it. main() Inside the main function, a SwingDemo object is created. The SwingDemo constructor is invoked with the following lines: SwingUtilities.invokeLater(new Runnable() { public void run() { new SwingDemo(); } }); This code requires a detailed explanation: • In general, Swing programs are event-driven. • An event is passed to the application by calling an event-handler. This event handler is defined by the application. • But the event-handler is executed on the event dispatching thread provided by Swing and not on the main thread of the application. • Although event handlers are defined by our program, they are called on a thread that was not created by our program. • SwigUtilities is a class that allows us to add Runnable objects to the system event queue. This class contains two methods called invokeLater() and invokeAndWait(). Prof. Mukesh N. Tekwani Page 11 of 42
  • 12. Java Swing Basics - 1 • • All Swing GUI components must be created and updated from the event-dispatching thread and not from the main thread. Thus main() cannot directly instantiate a SwingDemo object. It must create a Runnable object that executes on the event dispatching thread. To enable the GUI code to be created on the event dispatching thread, we must use one of these methods: o invokeLater() o invokeAndWait() Event Handling (Delegation Event Model) Event handling is at the core of GUI programming. Most events are generated by the user e.g., mouse click, typing in a text box, pressing a button, etc. But certain events can be system or application generated as well e.g., a timer event. Swing uses events which are packaged in javax.awt.event. Event handling is based on the event delegation model. This model defines a standard and consistent mechanism to generate and process events. The basic concept of this model is: (1) A source generates an event and sends it to one or more listeners. (2) The listener simply waits until it receives an event. (3) Once an event is received, the listener processes the event and then returns. (4) The advantage of this design is that the application logic that processes events is separated from the user interface logic that generates those events. (5) A user interface element is able to “delegate” the processing of an event to a separate piece of code. (6) In this model, listeners must register with a source in order to receive an event notification. (7) Since a listener is registered with a source, notifications are sent only to listeners that want to receive them. The three main actors in event handling are: Event or Event Object: 1. An event is an object that describes a state change in a source. 2. It can be generated by a user interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. 3. An event may be generated when a timer expires, a counter exceeds a value, software or hardware failure occurs, or an operation is completed. Such events are not user-generated. Page 12 of 42 mukeshtekwani@hotmail.com
  • 13. Java Swing Basics - 1 Event Sources: 1. A source is an object that generates an event. It is also called an event generator. This occurs when the internal state of that object changes in some way. 2. Sources may generate more than one type of event. 3. A source must register listeners in order for the listeners to receive notifications about a specific type of event. 4. Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Type is the name of the event and el is a reference to the event listener. E.g., the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ). 5. When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. Notifications are sent only to listeners that register to receive them. 6. Some sources may allow only one listener to register. The general form of such a method is this: public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException Type is the name of the event and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event. 7. A source must also provide a method that allows a listener to un-register an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener, we would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. Event Listeners 1. A listener is an object that is notified when an event occurs. It is also called as the event handler. 2. It must be registered with one or more sources to receive notifications about specific types of events. The event listener must implement methods to receive and process these notifications. 3. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. 4. Any object may receive and process one or both of these events if it provides an implementation of this interface. Prof. Mukesh N. Tekwani Page 13 of 42
  • 14. Java Swing Basics - 1 Swing Hierarchy: The Swing family tree: Layouts: Layouts control the way in which components are placed on the container. The layout defines how the components will be added (placed) to the container. Th layout manager automatically The arranges the controls within a window by using certain algorithms. Why are layout managers useful? Although we can lay out a few components manually, it is very manua difficult to place many components in this way. Sometimes the width and height information is not yet available when we have to arrange the co controls. The layouts commonly used are: 1. FlowLayout – this is the default layout manager. This implements a simple layout style manager. similar to the way text flows in a text editor – left to right. By default, components are laid out line-by-line beginning at the upper left corner. When a line is filled, layout moves to the next inning line. A small space is left between the components. Page 14 of 42 mukeshtekwani@hotmail.com
  • 15. Java Swing Basics - 1 The constructors for FlowLayout are: FlowLayout(); FlowLayout(int how); here we specify the alignment i.e. left, right, centre FlowLayout(int how, int horz, int vert); we also specify the horizontal and vertical spacing between the components. 2. BorderLayout – This layout provides four border regions and a center area. It divides the container in 5 regions called north, south, east and west. The middle area is called as center. The constructors for this are: BorderLayout(); BorderLayout(int horz, int vert); 3. GridLayout – This layout manager creates a two-dmensional grid in which the components are placed. We have to define the number of rows and columns in the grid. The components are placed left to right in the grid. The constructor methods are: GridLayout(); - this creates a single column grid layout. GridLayout(int rows, int cols); 4. CardLayout – This layout manager places the components behind each other. JTextField 1. This component is used to edit (enter) one line of text. 2. It is derived from the JTextComponent. JTextComponent provides the basic functionality common to Swing text components. 3. The three constructors of JText are: a. JTextField (int cols) b. JTextField (String str, int cols) c. JTextField (String str) 4. Here, str is a string and cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the given string. The cols field does not limit the number of characters that the user can enter. Example: textField = new JTextField(20); 5. JTextField generates events in response to user actions. a. The ActionEvent is fired when the user presses the Enter key. b. The CaretEvent is generated each time the cursor changes position. 6. We can only type in the text field that is “in focus”. A component receives focus when the user clicks the component. 7. To obtain the string currently in the text field, we use the getText() method. Prof. Mukesh N. Tekwani Page 15 of 42
  • 16. Java Swing Basics - 1 Methods of JTextField: Method void setColumns(int); int getColumns() void setHorizontalAlignment(int); int getHorizontalAlignment(); void setEditable(Boolean); boolean isEditable(); void setEchoChar(char); char getEchoChar(); Description Set number of columns displayed in the text field Returns the number of columns in the text field Sets how the text is aligned horizontally (JTextField.LEFT, JTextField.RIGHT, JTextField.CENTER) Gets how the text filed is aligned Sets whether the user can edit the text field gets whether the user can edit the text field Sets the echo character in a JPassword field) Gets the echo character in a JPassword field) Program 5 : Demonstration of Text Field: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JTextFieldDemo { public static void main(String[] args) { SimpleFrame Frame = new SimpleFrame(); Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Frame.setVisible(true); } } class SimpleFrame extends JFrame { JLabel label; JPanel showPanel, textFieldPanel; String sentence; JTextField textfield; public SimpleFrame() { int height = 200; int width = 300; setSize(width, height); setTitle("TextField example"); showPanel = new JPanel(); textFieldPanel = new JPanel(); label = new JLabel("Sentence"); Page 16 of 42 mukeshtekwani@hotmail.com
  • 17. Java Swing Basics - 1 showPanel.add(label); add(showPanel, BorderLayout.CENTER); textfield = new JTextField("Sentence", 20); textfield.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evento1) { String sentence=textfield.getText(); label.setText(sentence); } }); textFieldPanel.add(textfield); add(textFieldPanel, BorderLayout.SOUTH); } } Program : This example displays one text field and one password field import javax.swing.*; import java.awt.event.*; public class PassDemo extends JPanel { // create an object of the JLabel class JLabel lblName; JLabel lblPasswd; // create an object of the JPassword class JTextField txtName; JPasswordField txtPasswd; public PassDemo() { lblName = new JLabel("Enter User Name: "); txtName = new JTextField(10); Prof. Mukesh N. Tekwani Page 17 of 42
  • 18. Java Swing Basics - 1 lblPasswd = new JLabel("Enter Password: "); txtPasswd = new JPasswordField(10); txtPasswd.setEchoChar('*'); // Add tooltips to the text fields txtName.setToolTipText("Enter User Name"); txtPasswd.setToolTipText("Enter Password"); //Add labels to the Panel. add(lblName); add(txtName); add(lblPasswd); add(txtPasswd); } public static void main(String[] args) { // calls the PassDemo constructor. PassDemo demo = new PassDemo(); // set the text on the frame JFrame frm = new JFrame("Password Demo"); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setContentPane(demo); frm.setSize(275,300); frm.setVisible(true); } } // End of main() method // End of class declaration Output: Page 18 of 42 mukeshtekwani@hotmail.com
  • 19. Java Swing Basics - 1 JTextArea 1. A text area is a text control that lets the user enter multiple lines of text. 2. Text areas are implemented in Swing by the JTextArea class. 3. The constructor methods of this class are: • JTextArea(int rows, int cols) -- creates a text area with rows and columns • JTextArea(String str, int rows, int cols) – creates a text area with the specified text and rows and cols. Methods of JTextArea class: Method Description void setRows(int) void setFont(Font) insert(String str, int pos) Sets the number of rows for the text area Sets the font for the text area Inserts the specified text at the specified position in a text area. Returns the number of rows Returns the number of columns void getRows() void getColumns() import javax.swing.*; import java.awt.event.*; public class TextAreaDemo extends JPanel ActionListener { // creates two object of the JLabel class JLabel lblName, lblAdd; JTextField txtName, txtAdd; JTextArea taRemarks; JButton btn; public TextAreaDemo() { // To set the layout to none setLayout(null); //we set the positions implements manuualy by setBounds() lblName = new JLabel("Enter Your Name : "); lblAdd = new JLabel("Enter Your Address : "); txtName = new JTextField(15); txtAdd = new JTextField(25); taRemarks = new JTextArea(10,10); btn = new JButton("Process"); btn.addActionListener(this); Prof. Mukesh N. Tekwani Page 19 of 42
  • 20. Java Swing Basics - 1 // setBounds()is used to give the positioning of the objects lblName.setBounds(10, 20, 120, 25); //x, y, width, ht txtName.setBounds(150, 20, 150, 25); lblAdd.setBounds(10, 60, 150, 25); txtAdd.setBounds(150, 60, 200, 25); btn.setBounds(120, 100, 150, 30); taRemarks.setBounds(30,140,330,100); //Add all these components to the Panel. add(lblName); add(txtName); add(lblAdd); add(txtAdd); add(btn); add(taRemarks); } public void actionPerformed(ActionEvent actEvt) { if (actEvt.getSource() == btn) { taRemarks.append("Name:"+txtName.getText()+"n"); taRemarks.append("Address:"+txtAdd.getText()+"n"); } } public static void main(String[] args) { // calls the TextAreaDemo constructor. TextAreaDemo taDemo = new TextAreaDemo(); //set the text on the frame JFrame frm = new JFrame("Text Area Demo"); frm.setSize(400,300); frm.setContentPane(taDemo); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // To display the Frame frm.setVisible(true); } } Page 20 of 42 mukeshtekwani@hotmail.com
  • 21. Java Swing Basics - 1 Swing Buttons 1. Swing provides four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. 2. All these buttons are subclasses of the AbstractButton class. 3. The AbstractButton class has many methods that allow us to control the behaviour of buttons. E.g., we can display different icons when the button is disabled, pressed or selected. We can also have a rollover ion which is displayed when the mouse is positioned over a button. 4. The various methods are: a. void setDisabledIcon(Icon di) b. void setPressedIcon(Icon pi) c. void setSelectedIcon(Icon si) d. void setRolloverIcon(Icon ri) 5. The text associated with a button can be read or written using these methods: a. String getText() b. void setText(String str) 6. When the button is pressed, an ActionEvent is generated. JButton 1. 2. 3. 4. JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be displayed on the push button. The JButton class provides the functionality of a push button. The three constructors of JButton are: a. JButton (Icon icon) b. JButton(String str) c. JButton(String str, Icon icon) 5. When the button is pressed, an ActionEvent is generated. The following program illustrates the concepts of JButton and event handling. i. We create a frame whose panel has 3 buttons. ii. There are 3 listener objects that act as action listeners to the buttons. iii. Each time a user clicks on any of the buttons on the panel, the associated listener object then receives an ActionEvent that indicates a button click. In our sample program, the listener object will then change the background color of the panel. We now see how to create buttons and how to add them to a panel: i. We create a button by specifying a label string in the button constructor: JButton yellowButton = new JButton("Yellow"); ii. After creating a button, we add it to the panel using the add() method; we specify the component to be added: add(yellowButton); We now write the code that lets the panel listen to these buttons. We create classes that implement the ActionListener interface. This interface has one method called actionPerformed. This method takes an object of type ActionEvent as a parameter. When a button is clicked, we Prof. Mukesh N. Tekwani Page 21 of 42
  • 22. Java Swing Basics - 1 want to set the background color of the panel to a particular color. We store the desired color in the listener class. We then construct one object for each color and set the objects as button listeners. ColorAction yellowAction = new ColorAction(Color.YELLOW); yellowButton.addActionListener(yellowAction); If a user clicks on the button marked “Yellow,” then the actionPerformed method of the yellowAction object is called. Its backgroundColor instance field is set to Color.yellow, and it can now proceed to set the panel's background color. Program 6: To illustrate the JButton class. //To illustrate the JButton class import java.awt.*; import java.awt.event.*; import javax.swing.*; // A frame with a button panel class ButtonFrame extends JFrame { public ButtonFrame() { setTitle("ButtonTest"); setSize(300, 200); // add panel to frame ButtonPanel panel = new ButtonPanel(); add(panel); } } // A panel with three buttons. class ButtonPanel extends JPanel { public ButtonPanel() { // create buttons JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton("Blue"); JButton redButton = new JButton("Red"); // add buttons to panel add(yellowButton); add(blueButton); add(redButton); // create button actions Page 22 of 42 mukeshtekwani@hotmail.com
  • 23. Java Swing Basics - 1 ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); } // associate actions with buttons yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); //end of ButtonPanel // Actionlistener that sets the panel's background color. class ColorAction implements ActionListener { private Color backgroundColor; public ColorAction(Color c) { backgroundColor = c; } public void actionPerformed(ActionEvent event) { setBackground(backgroundColor); } } } public class ButtonTest { public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } Program 7: To illustrate the JButton class. This program will display 3 JButtons and assign shortcut keys and tooltip text to each button // To illustrate the JButton class // This program will display 3 JButtons and assign shortcut keys // and tooltip text to each button import java.awt.*; import java.awt.event.*; import javax.swing.*; // A frame with a button panel Prof. Mukesh N. Tekwani Page 23 of 42
  • 24. Java Swing Basics - 1 class ButtonFrame extends JFrame { public ButtonFrame() { setTitle("ButtonTest"); setSize(300, 200); // add panel to frame ButtonPanel panel = new ButtonPanel(); add(panel); } } // A panel with three buttons. class ButtonPanel extends JPanel { public ButtonPanel() { // create buttons JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton("Blue"); JButton redButton = new JButton("Red"); // add buttons to panel add(yellowButton); add(blueButton); add(redButton); } // create shortcut keys yellowButton.setMnemonic('Y'); blueButton.setMnemonic('B'); redButton.setMnemonic('R'); // add tooltips for each button yellowButton.setToolTipText("Yellow Color"); blueButton.setToolTipText("Blue Color"); redButton.setToolTipText("Red Color"); //end of ButtonPanel } public class ButtonTest3 { public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } Page 24 of 42 mukeshtekwani@hotmail.com
  • 25. Java Swing Basics - 1 Output: Tool tip text JToggleButton 1. A toggle button looks just like the push button but it acts differently because it has 2 states: pushed and released. 2. When we press the toggle button, it stays pressed and does not pop back as a regular button. When we press the toggle button a second time, it releases (or pops up). 3. Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. 4. JToggleButton is a superclass of JCheckBox and JRadioButton. Thus, JTogglebutton defines the basic functionality of all two-state components. 5. Constructors of JToggleButton: JToggleButton(String str) 6. By default the JToggleButton is in the off position. 7. JToggleButton generates two events each time it is pressed: (i) an action event, and (ii) an item event. When a JToggleButton is pressed in, it is selected and when it is popped out, it is deselected. Thus, the item event is used by those components that support selection. We now discuss the item event. (1) To handle item events, we must implement the ItemListener interface. (2) Whenever an item event is generated, it is passed to the itemStateChanged() method. (3) We determine the toggle button’s state by calling the isSelected() method. Program 7: To demonstrate the use of JToggleButton in an applet //Swing applet to illustrate the JToggleButton import javax.swing.*; import java.awt.*; import java.awt.event.*; /* <APPLET CODE = "JToggleButtonDemo" WIDTH = 200 HEIGHT = 80> </APPLET> */ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jbtn; public void init() Prof. Mukesh N. Tekwani Page 25 of 42
  • 26. Java Swing Basics - 1 { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI(); } } ); } } catch (Exception ex) { System.out.println("Can’t create because of " + ex); } //end of init() public void makeGUI() { setLayout(new FlowLayout()); //create a label jlab = new JLabel("Button is off"); //create a toggle button jbtn = new JToggleButton ("On / Off"); //Add an item listener for the toggle button jbtn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (jbtn.isSelected()) jlab.setText("Button is on"); else jlab.setText("Button is off"); } }); //add the toggle button and label to the content pane add(jbtn); add(jlab); } } Page 26 of 42 mukeshtekwani@hotmail.com
  • 27. Java Swing Basics - 1 To run this applet, at the DOS prompt type: C:> Appletviewer JToggleButtonDemo.java. Program 8: Write a program that illustrates the JButton class /* Use of JButton */ import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code = "ButtonTest2" width = 300 height = 100> </applet> */ public class ButtonTest2 extends JApplet implements ActionListener { JButton b1, b2; public void init() { b1 = new JButton("First Button"); b2 = new JButton("Second Button"); setLayout(new FlowLayout( )); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); //"this" allows the method to refer to the object that invoked it } public void actionPerformed(ActionEvent e) { if(e.getSource( ) == b1) showStatus("First Button Clicked"); Prof. Mukesh N. Tekwani Page 27 of 42
  • 28. Java Swing Basics - 1 else if(e.getSource( ) == b2) showStatus("Clicked on Second Button"); } } Program 9: Write a program to display radio buttons in a button group import java.awt.*; import java.awt.event.*; import javax.swing.*; class ToggleButtonDemo extends JFrame { public ToggleButtonDemo() { super("ToggleButton/ButtonGroup Demo"); // guess whats this? setLayout(new FlowLayout()); JToggleButton btn1 = new JToggleButton("Button 1", true); btn1.setToolTipText("This is button 1"); add(btn1); JToggleButton btn2 = new JToggleButton("Button 2", false); add(btn2); JToggleButton btn3 = new JToggleButton("Button 3", false); add(btn3); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(btn1); buttonGroup.add(btn2); buttonGroup.add(btn3); pack(); setVisible(true); } public static void main(String args[]) { new ToggleButtonDemo(); } } Page 28 of 42 mukeshtekwani@hotmail.com
  • 29. Java Swing Basics - 1 A ButtonGroup manages a set of buttons by ensuring that only one button within that group can be selected at any given time. Program 1: Program to display a frame with two images Write a Swing application that displays two command buttons on a JFrame. The buttons should display an image as well as text. //Swing program to display a frame with 2 images import javax.swing.*; import java.awt.*; class P4 extends JFrame { public P4() //constructor { JFrame jfrm = new JFrame("Displaying 2 images"); jfrm.setSize(300, 100); jfrm.setLayout(new FlowLayout()); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon img1 = new ImageIcon("twitter.png"); ImageIcon img2 = new ImageIcon("google.png"); JButton b1 = new JButton("Twitter", img1); JButton b2 = new JButton("Google", img2); jfrm.add(b1); jfrm.add(b2); jfrm.setVisible(true); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { new P4(); } Prof. Mukesh N. Tekwani Page 29 of 42
  • 30. Java Swing Basics - 1 }); } } Here is the output of the above code: In the above program we have used ImageIcon img1 = new ImageIcon("twitter.png"); ImageIcon is a Swing class; it encapsulates an image. The constructors of ImageIcon help to fetch the image from a file or URL. JWindow (7) A JWindow is a top-level container. (8) It can be displayed anywhere on the desktop. (9) JWindow does not have a title bar, and window-management buttons. (10) The user cannot move or resize the window. (11) It has no border. (12) The default layout for JWindow is BorderLayout. Program 2: Program to implement the JWindow class and display 2 buttons & a label. //Swing program to illustrate the JWindow import javax.swing.*; import java.awt.*; class JWindowDemo extends JWindow { public JWindowDemo() //constructor { JWindow jwin = new JWindow(); jwin.setSize(200, 100); JButton b1 = new JButton("ARTS"); JButton b2 = new JButton("SCIENCE"); JLabel lbl1 = new JLabel("COMMERCE"); jwin.setLayout(new BorderLayout()); jwin.add(b1, BorderLayout.EAST); jwin.add(lbl1, BorderLayout.WEST); jwin.add(b2, BorderLayout.CENTER); jwin.setVisible(true); } Page 30 of 42 mukeshtekwani@hotmail.com
  • 31. Java Swing Basics - 1 public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { new JWindowDemo(); } }); } } Layouts: Layouts control the way in which components are placed on the container. The layout defines how the components will be added (placed) to the container. The layout manager automatically arranges the controls within a window by using certain algorithms. Why are layout managers useful? Although we can lay out a few components manually, it is very difficult to place many components in this way. Sometimes the width and height information is not yet available when we have to arrange the controls. The layouts commonly used are: 5. FlowLayout – this is the default layout manager. This implements a simple layout style similar to the way text flows in a text editor – left to right. By default, components are laid out line-by-line beginning at the upper left corner. When a line is filled, layout moves to the next line. A small space is left between the components. The constructors for FlowLayout are: FlowLayout(); FlowLayout(int how); here we specify the alignment i.e. left, right, centre FlowLayout(int how, int horz, int vert); we also specify the horizontal and vertical spacing between the components. 6. BorderLayout – This layout provides four border regions and a center area. It divides the container in 5 regions called north, south, east and west. The middle area is called as center. The constructors for this are: BorderLayout(); BorderLayout(int horz, int vert); Prof. Mukesh N. Tekwani Page 31 of 42
  • 32. Java Swing Basics - 1 7. GridLayout – This layout manager creates a two-dmensional grid in which the components are placed. We have to define the number of rows and columns in the grid. The components are placed left to right in the grid. The constructor methods are: GridLayout(); - this creates a single column grid layout. GridLayout(int rows, int cols); 8. CardLayout – This layout manager places the components behind each other. JToggleButton 8. A toggle button looks just like the push button but it acts differently because it has 2 states: pushed and released. 9. When we press the toggle button, it stays pressed and does not pop back as a regular button. When we press the toggle button a second time, it releases (or pops up). 10. Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. 11. JToggleButton is a superclass of JCheckBox and JRadioButton. Thus, JTogglebutton defines the basic functionality of all two-state components. 12. Constructors of JToggleButton: JToggleButton(String str) 13. By default the JToggleButton is in the off position. 14. JToggleButton generates two events each time it is pressed: (i) an action event, and (ii) an item event. When a JToggleButton is pressed in, it is selected and when it is popped out, it is deselected. Thus, the item event is used by those components that support selection. We now discuss the item event. (4) To handle item events, we must implement the ItemListener interface. (5) Whenever an item event is generated, it is passed to the itemStateChanged() method. Page 32 of 42 mukeshtekwani@hotmail.com
  • 33. Java Swing Basics - 1 (6) We determine the toggle button’s state by calling the isSelected() method. Program 3: To demonstrate the use of JToggleButton in an applet //Swing applet to illustrate the JToggleButton import javax.swing.*; import java.awt.*; import java.awt.event.*; /* <APPLET CODE = "JToggleButtonDemo" WIDTH = 200 HEIGHT = 80> </APPLET> */ public class JToggleButtonDemo extends JApplet { JLabel jlab; JToggleButton jbtn; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI(); } } ); } catch (Exception ex) { System.out.println("Can’t create because of " + ex); } } //end of init() public void makeGUI() { setLayout(new FlowLayout()); //create a label jlab = new JLabel("Button is off"); //create a toggle button jbtn = new JToggleButton ("On / Off"); //Add an item listener for the toggle button jbtn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) Prof. Mukesh N. Tekwani Page 33 of 42
  • 34. Java Swing Basics - 1 { if (jbtn.isSelected()) jlab.setText("Button is on"); else jlab.setText("Button is off"); } }); //add the toggle button and label to the content pane add(jbtn); add(jlab); } } To run this applet, at the DOS prompt type: C:> Appletviewer JToggleButtonDemo.java. Program 4: Write a program that illustrates the JButton class /* Use of JButton */ import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code = "ButtonTest2" width = 300 height = 100> </applet> */ public class ButtonTest2 extends JApplet implements ActionListener { JButton b1, b2; public void init() { b1 = new JButton("First Button"); b2 = new JButton("Second Button"); setLayout(new FlowLayout( )); add(b1); add(b2); Page 34 of 42 mukeshtekwani@hotmail.com
  • 35. Java Swing Basics - 1 b1.addActionListener(this); b2.addActionListener(this); //"this" allows the method to refer to the object that invoked it } public void actionPerformed(ActionEvent e) { if(e.getSource( ) == b1) showStatus("First Button Clicked"); else if(e.getSource( ) == b2) showStatus("Clicked on Second Button"); } } Program 5: Write a program to display radio buttons in a button group import java.awt.*; import java.awt.event.*; import javax.swing.*; class ToggleButtonDemo extends JFrame { public ToggleButtonDemo() { super("ToggleButton/ButtonGroup Demo"); // setLayout(new FlowLayout()); JToggleButton btn1 = new JToggleButton("Button 1", true); btn1.setToolTipText("This is button 1"); add(btn1); JToggleButton btn2 = new JToggleButton("Button 2", false); add(btn2); JToggleButton btn3 = new JToggleButton("Button 3", false); add(btn3); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(btn1); buttonGroup.add(btn2); buttonGroup.add(btn3); pack(); setVisible(true); } public static void main(String args[]) { new ToggleButtonDemo(); } Prof. Mukesh N. Tekwani Page 35 of 42
  • 36. Java Swing Basics - 1 } A ButtonGroup manages a set of buttons by ensuring that only one button within that group can be selected at any given time. JCheckBox 1. The JCheckBox class provides functionality of a check box. 2. It is used to turn on and off an option. 3. JCheckBox has many constructors: JCheckBox() JCheckBox(String str) JCheckBocx(Icon icon) JCheckBox(Icon icon, boolean selected) JCheckBox(String string, boolean selected) JCheckBox(String string, Icon icon, boolean selected) creates an initially unselected check box with no text and no icon Creates a check box with specified text label creates an initially unselected check box with an icon Creates a check box with an icon and specifies whether or not it is initially selected – true or false.. Creates a check box with a text string and specifies whether or not it is initially selected – true or false. Creates a check box with an icon, a text string and specifies whether it is initially selected or not. 4. When the user selects or deselects a check box, am ItemEvent is generated. We can use the getItem() method to find the JCheckBox that generated the event. Methods of JCheckBox class: Method booloean getState() void setState(Boolean) String getLabel() void setLabel(String str) Description Get the status of the check box Set the state of the check box Get the label of the checkbox Set the label of the check box Program 6: This applet demonstrates the use of JCheckBox //JCheckBox demo import java.awt.*; import java.awt.event.*; import javax.swing.*; Page 36 of 42 mukeshtekwani@hotmail.com
  • 37. Java Swing Basics - 1 /* <APPLET CODE = "JCheckBoxDemo" width = 270 height = 50> </APPLET> */ public class JCheckBoxDemo extends JApplet implements ItemListener { JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI(); } } ); } catch (Exception ex) { System.out.println("Error: " + ex); } } //end of init() private void makeGUI() { //use flow layout setLayout(new FlowLayout()); //create check boxes, register listeners and add these //to container JCheckBox cb1 = new JCheckBox("C"); cb1.addItemListener(this); add(cb1); JCheckBox cb2 = new JCheckBox("C++"); cb2.addItemListener(this); add(cb2); JCheckBox cb3 = new JCheckBox("Java"); cb3.addItemListener(this); add(cb3); JCheckBox cb4 = new JCheckBox("C#"); cb4.addItemListener(this); add(cb4); Prof. Mukesh N. Tekwani Page 37 of 42
  • 38. Java Swing Basics - 1 } //create a label and it it to content pane jlab = new JLabel("Select languages"); add(jlab); //end of makeGUI //Handle events for check boxes public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); //we obtain a reference to the checkbox object that //caused the event if (cb.isSelected()) jlab.setText(cb.getText() + " is selected "); else jlab.setText(cb.getText() + " is cleared "); } } JComboBox 1. A combo box is a combination of a text field and a drop-down list. 2. A combo box normally displays only one entry but it will also display a drop-down list that allows the user to select a different entry. 3. The JComboBox object is created with default choices. 4. The JComboBox constructor that is used to initialize a combo box with array elements is : JComboBox(Object[] items). Here, items is an array that initializes the combo box. 5. In addition to passing array of items to be displayed, we can also add items dynamically by using the add() method as follows: addItem(Object obj) 6. The JComboBox generates an action event when the user selects an item from the list. 7. The JComboBox also generates an item event when an item is selected or deselected. Therefore, changing a selection means two item events will occur: one for the selected item and the other for the deselected item. 8. We can get the item selected by using the getSelectedItem() method. We must cast the returned value into the type of object stored in the list. 9. The JComboBox has a method called setEditable(). This can be used to enable or disable entry of text into the text field of the combo box. Methods of JComboBox class: Method void addItem(object) void insertItem(object, int) void removeItemAt( int) void removeAllItem() int getItemCount() Page 38 of 42 Description Add an object into the combo box Insert an object into the combo box at the specified index. Removes the item from the specified position Removes all items from the combo box Get the number of items in the combo box mukeshtekwani@hotmail.com
  • 39. Java Swing Basics - 1 Object getItemAt(int) Object getSelectedItem() boolean getState() void setState(Boolean) selectedItemChanged() Get an item from the specified position. Returns an array of the selected items Get the status of a check box Set the status of a check box. This method is called when the selected item is changed JTabbedPane 1. JTabbedPane is simply a stack of components in selectable layers. Each layer can contain one component which is normally a container. 2. These components are linked with tabs. Selecting a tab causes the component associated with that tab to come in front. 3. JTabbedPane has following constructors. a. The default constructor creates an empty control with the tabs positioned across the top of the pane. b. The constructor JTabbedPane(int tabposition) creates an empty tabbed pane and the tabposition can be one of these: JTabbedPane.TOP, JTabbedPane.bottom, JTabbedPane.left, OR JTabbedPane.right 4. Tabs are added by invoking the addTab() method. Its general syntax is void addTab(String name, Component comp) Here, name is the name of the tab and component is the component that has to be added to the tab. The component is usually JPanel Program 7: To create a tabbed pane consisting of three tabs called “Cities”, “Colors” and “Flavours”. Each tab has an associated pane which can contain components. import javax.swing.*; /* < APPLET CODE ="JTabbedPaneDemo" width=400 height=100> </APPLET> */ public class JTabbedPaneDemo extends JApplet { public void init() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); Prof. Mukesh N. Tekwani Page 39 of 42
  • 40. Java Swing Basics - 1 jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } } //end of class CitiesPanel class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3); } } //end of class ColorsPanel class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox jcb = new JComboBox(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb); mukeshtekwani@hotmail.com Page 40 of 42
  • 41. Java Swing Basics - 1 } } //end of class FlavorsPanel JScrollPane 1. A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary. 2. Scroll panes are implemented in Swing by the JScrollPane class. 3. Some of its constructors are shown here: a. JScrollPane(Component comp) b. JScrollPane(int vsb, int hsb) Here, comp is the component to be added to the scroll pane. vsb and hsb are constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the ScrollPaneConstants interface. Program : To use the JScrollPane class to display a scrollable image import javax.swing.*; public class JScrollPaneDemo extends JFrame { public JScrollPaneDemo() { super("JScrollPane Demo"); ImageIcon ii = new ImageIcon("india.gif"); JScrollPane jsp = new JScrollPane(new JLabel(ii)); add(jsp); setSize(300,250); setVisible(true); } public static void main(String[] args) { new ScrollPaneDemo(); } } JPanel 1. A JPanel is Swing container that is used for grouping components in an area of an applet or an application. 2. A panel can also be used to group other panels. Prof. Mukesh N. Tekwani Page 41 of 42
  • 42. Java Swing Basics - 1 3. Swing panel is represented by the JPanel class; it is stored in the javax.swing.JPanel package. 4. JPanel is a lightweight component. Steps to add a component to JPanel and then add a Panel to a the Frame: (1) Create a JFrame object: JFrame jfrm = new JFrame(); (2) Create a JPanel object: JPanel jpnl = new JPanel(); (3) Add all the components (which can be containers) to the JPanel object by using its add() method. pnl.add(<component name>); (4) The JPanel object is made part of the content pane by calling the setContentPane() method of the JFrame class. frm.setContentPane(pnl); Page 42 of 42 mukeshtekwani@hotmail.com