Download presentation
Presentation is loading. Please wait.
1
Chapter-2 Java Programming COMP-417
GUI Components
2
GUI COMPONENTS A graphical user interface presents a user-friendly mechanism for interacting with an application. A GUI gives an application a distinctive look and feel Providing different applications with consistent, intuitive user-interface components gives users a sense of familiarity with a new application, so that they can learn it more quickly. GUIs are built from GUI components sometimes called controls or widgets.
3
Overview of Swing Components
Most Swing GUI components are located in package javax.swing. Together, the appearance and the way in which the user interacts with the application are known as that application’s look-and-feel. Swing GUI components allow you to specify a uniform look- and-feel for your application across all platforms or to use each platform’s custom look-and-feel. Lightweight Swing components are not tied to actual GUI components supported by the under- lying platform on which an application executes. Several Swing components are heavyweight components that require direct interaction with the local windowing system which may restrict their appearance and functionality. Class Component package java.awt) declares many of the attributes and behaviors com- mon to the GUI components in packages java.awt and javax.swing. Class Container isa subclass of Component. Components are attached to Containers so the Components can be organized and displayed on the screen. Class JComponent of package javax.swing is a subclass of Container. JComponent is the su- perclass of all lightweight Swing components and declares their common attributes and behaviors. Some common JComponent features include a pluggable look-and-feel shortcut keys called mnemonics tool tips support for assistive technologies and support for user-interface localization
4
Swing package Overview of Swing Components
5
Comparison between AWT & Swing Component
Java Swing
6
import javax.swing.*; import java.awt.*; public class JButtonDemo extends JFrame { JButton b1; public JButtonDemo() { Container c = getContentPane(); setLayout(new FlowLayout()); b1 = new JButton("Java"); c.add(b1); }
7
public static void main(String[] args) {
JButtonDemo b= new JButtonDemo(); b.setSize(275,110); b.setVisible(true); b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
8
By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
Event Handling By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
9
By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
Normally, a user interacts with an application’s GUI to indicate the tasks that the application should perform, For example, when you write an to the specified addresses. GUI are event driven. When the user interacts with a GUI component, the interaction– known as an event --- drives the program to perform a task. Some common user interactions that cause an application to perform a task include clicking a button, typing in a text field, selecting an item from a menu, closing a window and moving the mouse. The code that performs a task in response to an event is called an event handler, and the overall process of responding to events is known as event handling. By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
10
Steps Required to Set Up Event Handling for a GUI Component
Create a class that represents that event handler. Implement an appropriate interface, known as an event-listener interface, in the class from Step1. Indicate that an object of the class from Steps1 and 2 should be notified when the event occurs. This is known as registering the event handler. By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
11
JAVA PROGRAMMING COMP-417
Object Action Event ContainerEvent EventObject AdustmentEvent FocusEvent AWTEvent ItemEvent PaintEvent TextEvent WindowEvent Some event classes of package java.awt.event ComponentEvent InputEvent KeyEvent MouseEvent By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A MouseWheelEvent By Mohammed Ali Sohail
12
JAVA PROGRAMMING COMP-417
Java.util.EventListener ActionListener AdjustmentListgener ComponentListener ContainerListener FocusListener ItemListener Some common event-listener interfaces of package java.awt.event MouseListner KeyListener MouseMotion Listener TextListener WindowListener By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A By Mohammed Ali Sohail
13
Delegation Event Model
JAVA PROGRAMMING COMP-417 Delegation Event Model There are three important parts to the event- handling mechanism. event source: It is the GUI component with which the user interacts. event object : The event object encapsulates information about the event that occurred, such as a reference to the event source and any event-specific information that may be required by the event listener for it to handle the event. event listener: is an object that is notified by the event source when an event occurs; in effect, it “listens ” for an event, and one of its methods executes in response to the event. A method of the event listener receives an event objects when the event listener is notified of the event. The event listener then uses the event object to respond to the event. This event handling model is known as the delegation event model--- an event’s processing is delegated to an object(the event listener) in the application. For each event-object type, there is typically a corresponding event-listener interface. An event listener for a GUI event is an object of a class that implements one or more of the event-listener interfaces from packages java.awt.event and javax.swing.event. Each event- listener interface specifies one or more event-handling methods that must be declared in the class that implements the interface. When an event occurs, the GUI component with which the user interacted notifies its registered listener's by calling each listener’s appropriate event-handling method. for example, when the user presses the Enter key in a JTextField, the registered listener’s actionPerformed method is called. Delegation Event Model By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A By Mohammed Ali Sohail
14
JAVA PROGRAMMING COMP-417
handler t1 TextFieldHandler object public void actionPerformed( ActionEvent e ) { //event handled here } JTextField object listenerList Event registration for JTextField textField1 This reference is created by the statement t1. addActionListener(th); By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A By Mohammed Ali Sohail
15
By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextFieldDemo extends JFrame { JTextField t1, t2,t3; JPasswordField pf; public TextFieldDemo() setLayout(new FlowLayout()); t1 = new JTextField(10); add(t1); t2= new JTextField("Enter text here"); add(t2); t3= new JTextField("Uneditable text filed",21); t3.setEditable(false); add(t3); pf=new JPasswordField("Hidden text"); add(pf); TextFieldHandler th = new TextFieldHandler(); t1.addActionListener(th); t2.addActionListener(th); t3.addActionListener(th); pf.addActionListener(th); } By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A
16
JAVA PROGRAMMING COMP-417
class TextFieldHandler implements ActionListener { public void actionPerformed(ActionEvent e) String s=""; if(e.getSource()==t1) s=String.format("textField1:%s ", e.getActionCommand()); else if(e.getSource()==t2) s=String.format("textField2:%s", e.getActionCommand()); else if(e.getSource()==t3) s=String.format("textField3:%s", e.getActionCommand()); else if(e.getSource()==pf) s=String.format("passwordField:%s", e.getActionCommand()); JOptionPane.showMessageDialog(null,s); }}} JAVA PROGRAMMING COMP-417 Handler class By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A By Mohammed Ali Sohail
17
JAVA PROGRAMMING COMP-417
import javax.swing.*; public class TextFieldTest { public static void main (String[] args) TextFieldDemo tfd=new TextFieldDemo(); tfd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); tfd.setSize(350,100); tfd.setVisible(true); } Main class By Mohammed Ali Sohail Lecturer Jazan University, Jazan K.S.A By Mohammed Ali Sohail
18
Layout Manager
19
Layout manager: A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setLayout() method.If no call to setLayout() is made,then the default manager is used. Whenever a container is resized, the layout manager is used to position each of the components within it. Java has several predefined LayoutManager classes. FlowLayout BorderLayout GridLayout CardLayout GridBagLayout
20
FlowLayout:FlowLayout is the default layout manager.
Therefore,by default, components are laidout line-by-line beginning at the upper-left corner. FlowLayout.LEFT FlowLayout.CENTER(default) FlowLayout.RIGHT Example: FlowLayout ft = new FlowLayout();
21
Border Layout:- The BorderLayout class implements a common layout
Border Layout:- The BorderLayout class implements a common layout.style for top-level windows, It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north,south,east and west.The middle area is called the center. BorderLayout defines the following constants that specify the regions. BorderLayout.CENTER BorderLayout.EAST BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.WEST 3) GridLayout:- It lays out components in a two-dimensional grid. The constructors supported by GridLayout are shown here. GridLayout() GridLayout(int numRows,int numColumns) c)GridLayout(int numRows, int numColumns,int horz,int vert)
22
The first form creates a single-column grid layout
The first form creates a single-column grid layout. The second form creates a grid layout with the specified numbers of rows and columns. The third form allows you to specify the horizontal and vertical space left between components in horz and vert espectively .
23
CardLayout:- The CardLayout class is unique among the other Managers in that it stores several different layouts. CardLayout provides these two constructors: Cardalyout() CardLayout(int horz,int vert) The first form creates a default card layout. The second form allows you to specify the horizontal and vertical space left between components in horz and vert,respectively.
24
GridBagLayout:-GridBagLayout is a bit more complicated
than the other layout managers,it is still quite easy to use once You understand how it works. The location and size of each component in a Grid bag are determined by a set of constraints linked to it. The Constraints are contained in an object of type GridBagConstraints.constarints include the height and width of a cell.and the placement of a component, its alignment, and its anchor point within the cell. The general procedure for using a grid bag is to first create a new GridBagLayout object and make it the current layout manager.Then,set the constraints that apply to each component that will be added to the grid bag.Finally, add the components to the layout manager.
25
GridBagLayout defines only one constructor,which is shown here.
GridBagConstraints defines several fields that you can set to govern the size,placement and specing of a component. GridBagLayout gb=new GridBagLayout( ); Must added with GridBagConstraints object. GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=i; //column counting from 0 gbc.gridy=i;//row counting from 0 gbc.gridwidth=i;// Numbers of columns wide(default 1) gbc.gridheight=i;//numbers of rows high(default 1) gbc.weightx=d;//Relative horizontal space to allocate if container expands Default 0.0
26
gbc.weighty=d;//Relative vertical space to allocate if containerexpands Default 0.0
gbc.fill=fill //How to expand component if space larger than preferred size. Fill can be GridBagConstraints.NONE GridBagConstraints.VERTICAL GridBagConstraints.HORIZONTAL GridBagConstraints.BOTH gbc.anchor=anch;//Specifies the location of a component within a cell. If component does n’t fill the space,tells how it should be Aligned and anch can be one of these. GridBagConstraints.CENTER GridBagConstraints.NORTH GridBagConstraints.SOUTH GridBagConstraints.NORTHEAST GridBagConstraints.NORTHWEST GridBagConstraints.SOUTHEAST GridBagConstraints.SOUTHWEST GridBagConstraints.WEST gbc.insets= ins;//Space around component. Example: Gbc.insets=new Insets(10,0,0,0);
27
Example for layout
28
import java.awt.*; import javax.swing.*; public class GridLayoutDemo { public final static boolean RIGHT_TO_LEFT = false; public static void addComponentsToPane(Container contentPane) { if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); } // Any number of rows and 2 columns contentPane.setLayout(new GridLayout(1,2)); contentPane.add(new JLabel("JLabel 1")); contentPane.add(new JButton("JButton 2")); contentPane.add(new JCheckBox("JCheckBox 3")); contentPane.add(new JTextField("Long-Named JTextField 4")); contentPane.add(new JButton("JButton 5"));
29
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane and components in GridLayout addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); });
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.