Object-Oriented Programming
This presentation is the property of its rightful owner.
Sponsored Links
1 / 145

Object-Oriented Programming PowerPoint PPT Presentation


  • 141 Views
  • Uploaded on
  • Presentation posted in: General

Object-Oriented Programming. Chapter 5 (1): GUI in Java. Agenda. Layeout Mangement FlowLoyout BorderLayout GridLayout …. Introduction Simple GUI-Based IO with JOptionPane . AWT vs swing Containers and Components Introduction to Components Jlable Jbotton …. Introduction.

Download Presentation

Object-Oriented Programming

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Object oriented programming

Object-Oriented Programming

Chapter 5 (1): GUI in Java


Object oriented programming

Agenda

  • Layeout Mangement

    • FlowLoyout

    • BorderLayout

    • GridLayout

    • ….

  • Introduction

  • Simple GUI-Based IO with JOptionPane.

  • AWT vs swing

  • Containers and Components

  • Introduction to Components

    • Jlable

    • Jbotton


Object oriented programming

Introduction

  • A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application.

  • It gives an application a distinctive “look” and “feel.” Providing different applications with consistent, intuitive user interface components allows users to be somewhat familiar with an application, so that they can learn it more quickly and use it more productively.

  • GUIs are built from GUI components. These are sometimes called controls or widgets—short for window gadgets—in other languages.

  • A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition.


Object oriented programming

Introduction

  • A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition.

  • In this chapter you will earn about many of Java’s GUI components.


Object oriented programming

Simple GUI-Based I/O with JOptionPane

  • The following simple addition application uses two input dialogs to obtain integers from the user and a message dialog to display the sum of the integers the user enters.

    import javax.swing.JOptionPane;

    public class Addition {

    public static void main( String args[] ) {

    String firstNumber =

    JOptionPane.showInputDialog( "Enter first integer" );

    int number1 = Integer.parseInt( firstNumber );

    String secondNumber =

    JOptionPane.showInputDialog( "Enter second integer" );

    int number2 = Integer.parseInt( secondNumber );

    int sum = number1 + number2; // add numbers

    JOptionPane.showMessageDialog( null, "The sum is " + sum,

    "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );

    }

    }


Object oriented programming

Simple GUI-Based …

  • Java’s JOptionPaneclass(package javax.swing)providesprepackaged dialog boxes for both input and output.

  • These dialogs are displayed by invoking staticJOptionPane methods.

    • showInputDialogmethod displays an input dialog using the method’s String argument ("Enter first integer") as a prompt . It has a text box and two buttons ok and Cancel

    • showMessageDialog method is used to display a message dialog containing the sum.

      • Thefirstargument helps the Java application determine where to position the dialog box.

      • The valuenullindicates that the dialog should appear in the center.

      • It can also be used to specify that the dialog should appear centered over a particular window of the computer screen.


Object oriented programming

Simple GUI-Based…

  • Thesecondargument is the message to display—in this case, the result of concatenating the String "The sum is " and the value of sum.

  • Thethirdargument—"Sum of Two Integers"—represents the string that should appear in the dialog’s title bar at the top of the dialog.

  • The fourth argument:- JOptionPane.PLAIN_MESSAGE—is the type of message dialog to display. A PLAIN_MESSAGEdialog does not display an icon to the left of the message. Other possible constants are: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE

  • Class JOptionPane provides several overloaded versions of methods showInputDialogand showMessageDialog, as well as methods that display other dialog types.


  • Object oriented programming

    AWT vs Swing

    • Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing.

    • When java was introduced, the GUI classes were bundled in a library known as Abstract Windows Toolkit(AWT).

    • AWT (Abstract Window Toolkit) is Java’s original set of classes for building GUIs.

      • Uses peer components of the OS; heavyweight

      • AWT uses the native operating system's window routines so the visual effect is dependent on the run-time system platform.


    Object oriented programming

    AWT vs Swing

    • For every platform on which Java runs, the AWT components are automatically mapped to the platform-specific components through their respective agents, known as peers.

    • Not truly portable: looks different and lays out inconsistently on different OSs. The application's GUI components display differently on each platform.

  • AWT is adequate for many applications but it is difficult to build an attractive GUI


  • Object oriented programming

    AWT vs Swing

    • Swing is designed to solve AWT’s problems (present since Java 2 )

      • 99% java; lightweight components

        • Drawing of components is done in java

      • Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms.

      • Lays out consistently on all Oss

      • Much bigger set of built-in components

      • Uses AWT event handling


    Object oriented programming

    AWT vs Swing…

    • Swing is built “on top of” AWT, so you need to import AWT and use a few things from it

    • Swing is bigger and slower

    • Swing is more flexible and better looking

    • Swing and AWT are incompatible--you can use either, but you can’t mix them

      • Actually, you can, but it’s tricky and not worth doing

    • Basic components/controls are practically the same in both

      • AWT: Button b = new Button ("OK");

      • Swing: JButton b = new JButton("OK");

    • Swing gives far more options for everything (buttons with pictures on them, etc.)

    • AWT classes are contained inside package java.awt while swing classes are located in package javax.swing.


    Object oriented programming

    GUI Class Hierarchy

    12


    Object oriented programming

    GUI Classes

    • The GUI classes can be classified into three groups: container class, helper class, and component classes.

      Container classes

      • A GUI is built by putting components/controls into containers.

      • Container is used to group components. Frames, Panels and applets are examples of containers.

      • Important Container classes areJFrame, JApplet, and JPanel.


    Object oriented programming

    GUI Classes

    JFrame

    • A resizable, movable window with title bar and close button. Usually it contains JPanels.

    • It is a containers that holds other Swing user-interface components in Java GUI application.

      JPanel

    • A region internal to a JFrame or another JPanel. Used for grouping components together. Optionally bounded by a visible border. Lives inside some enclosing Container.

    • Panels can be nested. You can place panels inside a container that includes a panel.


    Object oriented programming

    GUI Classes…

    • The terms “pane” and “panel” are used interchangeably in Java.

    • If a frame is a window, a pane is the glass.

    • Panes hold a window’s GUI components.

    • Every frame has at least one pane, the default “Content Pane”

      JApplet

    • Is a subclass of Applet .

    • represents the featureless Window provided by the browser for an Applet to run in.


    Object oriented programming

    Container Classes

    Container classes can contain other GUI components.

    16


    Object oriented programming

    GUI Classes…

    GUI Components or controls (also known as "widgets")

    • Are the basic user interface elements the user interacts with: labels, buttons, text fields, ...

    • The visual arrangement of the components depends on the container's layout.

    • When the user does something to a component, the component's listener is sent an event.


    Object oriented programming

    Swing GUI Components

    18


    Object oriented programming

    Swing GUI Components

    • Input Components

      • Buttons ( JButton, JRadioButtons, JCheckBox)

      • Text (JTextField, JTextArea)

      • Menus (JMenuBar, JMenu, JMenuItem)

      • Sliders (JSlider)

      • JComboBox (uneditable) (JComboBox)

      • List (Jlist )

    • Information Display Components

      • JLabel

      • Progress bars (JProgressBar)

      • Tool tips (using JComponent's setToolTipText(s) method)

    • Choosers

      • File chooser (JFileChooser)

      • Color chooser (JColorChooser)


    Object oriented programming

    Swing GUI Components …

    • More complex displays

      • Tables (JTable)

      • Trees (JTree)

      • Formatted Text

    • Every GUI components has

      • Properties

      • Methods

      • Events

    JButton


    Object oriented programming

    GUI Class…

    GUI Helper Classes

    • They are used to describe the properties of GUI components such as graphics context, colors, fonts, and dimension.

      Graphics

      • Is an abstract class that provides a graphical context for drawings strings, lines, and simple shapes.

        Color:

      • Deals with the colors of GUI components.

        For example:- you can specify background colors in components like Jframe and Jpanel. You can specify colors of lines, shapes,…..


    Object oriented programming

    GUI Class…

    Font

    • Specify fonts for the text and drawings on GUI components.

      Example:- You can specify the font type(e.g. SansSerif), style (e.g. bold), and size(e.g. 24 points) for the text on the button.

      LayoutManager

    • Is an interface whose instances specify how components are arranged in a container.

  • The helper classes are in the java.awt package. The Swing components do not replace all the classes in AWT, only AWT GUI components classes (e.g. Button, TextField, TextArea). The AWT is helper classes remain unchanged.


  • Object oriented programming

    GUI Helper Classes

    23


    Object oriented programming

    Steps to build a GUI

    • Make a Container – you need to create either a frame or an applet to hold the user-interface components.

    • Create some more Components (buttons, text areas, etc.).

    • Add your Components to your display area - Choose a layout manager.

    • Attach Listeners to your Components - interacting with a Component causes an Event to occur.


    Object oriented programming

    Creating a Frames

    Frame

    • Is an independent window that has decorations such as a border, a title and buttons for closing, minimizing and maximizing the window.

    • Frame is a window that is not contained inside another window.

    • Can be moved around on the screen independently of any other GUI windows.

    • Applications with a GUI typically use at least one frame.

    • Frame is the basis to contain other user interface components in Java GUI applications.


    Object oriented programming

    Creating a Frames


    Object oriented programming

    Frame

    • The JFrame class can be used to create windows.

    • For Swing GUI programs, use JFrame class to create widows.


    Object oriented programming

    JFrame


    Object oriented programming

    JFrames…

    JFrame Class Methods

    29


    Object oriented programming

    JFrames…

    JFrame Class Methods

    • public void setBounds(int x, int y, int width, int

    • height)

    • Specifies the size of the frame and the location of the upper

    • left corner.

    • This puts the upper left corner at location (x, y), where x the

    • the number of pixels from the left of the screen and y is is the

    • number from the top of the screen. height and width are as

    • before.

    30


    Object oriented programming

    JFrames…

    JFrame Class Methods

    • public void setDefaultCloseOperation(int mode)

    • Is used to specify one of several options for the close button. Use one of the following constants to specify your choice:

    • JFrame.EXIT_ON_CLOSE:- Exit the application.

    • JFrame.HIDE_ON_CLOSE:- Hide the frame, but keep the application running.

    • JFrame.DO_NOTHING_ON_CLOSE:- Ignore the click.

    31


    Object oriented programming

    JFrame…

    import javax.swing.*;

    public class JFrameSample {

    public static void main(String[] args) {

    JFrame frame = new JFrame(“First JFrame");

    frame.setSize(400, 300);

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setVisible(true);

    }

    }


    Object oriented programming

    JFrame…

    • The frame is not display until the frame.setVisibile(true) method is invoked.

    • frame.setSize(400, 300)specifies that the frame is 400 pixels wide and 300 pixels high.

    • If thesetSizeand setVisible methods are both defined in the component class, they are inherited by the JFrame class.

    • Invoking setLocationRelativeTo(null)centers the frame on the screen.


    Object oriented programming

    JFrame…

    • Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

      tells the program to terminate when the frame is closed.

    • If you forget to call setDefaultCloseOperation() you will get JFrame.HIDE_ON_CLOSE by default. Thus the program does not terminate when the frame is closed. In that case, you have to stop the program by pressing Ctrl + C.


    Object oriented programming

    JFrame…

    import javax.swing.JFrame;

    publicclass Simple extends JFrame {

    public Simple() {

    setSize(300, 200);

    setTitle("First JFrame");

    setLocationRelativeTo(null);

    SetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setVisible(true);

    }

    publicstaticvoid main(String[] args) {

    Simple simple = new Simple();

    }

    }


    Object oriented programming

    JFrame…

    • The setTitle(String text) method is defined in the

    • java.awt.Frame class.

    • Since JFrame is subclass of Frame, you can use it to se a title

    • for an object of JFrame.

    • The constructor Simple() does not explicitly invoke

    • the constructor JFrame(). But the constructor JFrame() is

    • invoked implicitly. (Constructor Chaining).


    Object oriented programming

    Adding Components into a Frame


    Object oriented programming

    GUI Components

    • Introduces the frequently used GUI components

    38


    Object oriented programming

    JButton

    • A button is a component that triggers an action event

      when clicked.

    • Swing provides regular buttons, toggle buttons, check

      box buttons, and radio buttons.

    • The common features of these buttons are generalized in

      javax.swing.AbstractButton.

    • JButtoninherits AbstractButton and provides several

      constructors to create buttons.

    39


    Object oriented programming

    JButton

    JButton Constructors.

    40


    Object oriented programming

    JButton

    The following are JButton constructors:

    JButton()

    • Creates a default button with no text and icon.

      JButton(Icon icon)

    • Creates a button with an icon.

      JButton(String text)

    • Creates a button with text.

      JButton(String text, Icon icon)

    • Creates a button with text and an icon.

    41


    Object oriented programming

    JButton

    42


    Object oriented programming

    JButton

    JButton Properties

    • text

    • icon

    • mnemonic

    • horizontalAlignment

    • verticalAlignment

    • horizontalTextPosition

    • verticalTextPosition

    • iconTextGap

    43


    Object oriented programming

    JButton

    Some UsefulJButtonMethods

    public void setText(String text)

    • Sets the button's text.

      public String getText()

    • Returns the button's text.

      public void setEnabled(boolean b)

  • Enables (or disables) the button.


  • Object oriented programming

    JButton

    Some usefulJButtonMethods

    public void setSelectedIcon(Icon selectedIcon)

    • Sets the selected icon for the button.

      public boolean isSelected()

    • Returns the state of the button. True if the toggle button is selected, false if it's not.


    Object oriented programming

    JLabel

    A label is a display area for a short text(a non-editable), an image, or both.

    46


    Object oriented programming

    JLabel

    The constructors for labels are as follows

    • JLabel()

      • Creates a default label with no text and icon.

    • JLabel(String text)

      • Creates a label with text.

    • JLabel(Icon icon)

      • Creates a label with an icon.

    • JLabel(String text, int horizontalAlignment)

      • Creates a label with an text and the specified horizontal

      • alignment.

    47


    Object oriented programming

    JLabel

    The constructors for labels are as follows:

    • JLabel(Icon icon, int horizontalAlignment)

      • Creates a label with an icon and the specified horizontal

      • alignment.

    • JLabel(String text, Icon icon, int

    • horizontalAlignment)

      • Creates a label with text, an icon, and the specified horizontal

      • alignment.

    48


    Object oriented programming

    JLabel

    JLabelProperties

    • JLabel inherits all the properties from JComponent and has

      many properties similar to the ones in JButton, such as

      text, icon, horizontalAlignment,

      verticalAlignment, horizontalTextPosition,

      verticalTextPosition, and iconTextGap.

    49


    Jlabel

    JLabel

    Jlabel…

    Some Useful JLabel Methods

    public String getText()

    • Returns a string containing the text in the label component

      public void setText(String)

    • Sets the label component to contain the string value

      public Icon getIcon()

    • Returns the graphic image (icon) that the label displays.

      public void setIcon(Icon icon)

    • Defines the icon this component will display. If the value of icon is null, nothing is displayed.


    Object oriented programming

    JLabel

    Using Labels

    // Create an image icon from image file

    ImageIcon icon = new ImageIcon("image/grapes.gif");

    // Create a label with text, an icon, with centered horizontal alignment

    JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER);

    // Set label's text alignment and gap between text and icon

    jlbl.setHorizontalTextPosition(SwingConstants.CENTER);

    jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);

    jlbl.setIconTextGap(5);

    51


    Object oriented programming

    JTextField

    • A text field is a box that contains a line of text. The user can

      type text into the box and the program can get it and then use

      it as data.

    • The program can write the results of a calculation to a

      Text Field.

    • Text fields are useful in that they enable the user to enter in

      variable data (such as a name or a description).

    • JTextField is swing class for an editable text display.

    52


    Object oriented programming

    JTextField

    53


    Object oriented programming

    JTextField

    JTextFieldConstructors:

    • JTextField(int columns)

      Creates an empty text field with the specified number of columns.

    • JTextField(String text)

      Creates a text field initialized with the specified text.

    • JTextField(String text, int columns)

      Creates a text field initialized with the specified text and the column size.

    54


    Jtextfield properties

    JTextField

    JTextFieldProperties

    • text

    • horizontalAlignment

    • editable

    • columns

    55


    Jtextfield methods

    JTextField

    JTextFieldMethods

    • public String getText()

      Returns the string from the text field.

    • public void setText(String text)

      Puts the given string in the text field.

    • public void setEditable(booleaneditable)

      Enables or disables the text field to be edited. By default, editable is true.

    • public void setColumns(int)

      Sets the number of columns in this text field.The length of the text field is changeable.

    56


    Jtextfield methods1

    JTextField

    JTextFieldMethods

    public void select(int selectionStart, int selectionEnd)

    • Selects the text between the specified start and end positions.

      public String getSelectedText()

    • Returns the text value that has been highlighted in the text field.

      public void append(Stringvalue)

    • Appends the text value of the string to the already existing text in the component

    57


    Using text fields

    JTextField

    Using Text Fields

    JLabel Fname= new JLabel("First Name");

    JTextField text = new JTextField(10);

    JLabel Lname= new JLabel("Last Name");

    JTextField text1 = new JTextField("Text1",10);

    jtf.setEditable(false);

    add(Fname); add(text); add(Lname); add(text1);

    58


    Object oriented programming

    JPasswordField….

    • Allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.

    • JPasswordField class is subclass of JTextField class.


    Object oriented programming

    JPasswordField…


    Object oriented programming

    JPasswordField….

    • JLabel lb = new JLabel(“Password”);

    • JPasswordField password = new JPasswordField(10);


    Object oriented programming

    JTextArea

    • If you want to let the user enter multiple lines of text, you

      cannot use text fields unless you create several of them.

    • The solution is to use JTextArea class, which enables

      the user to enter multiple lines of text.

    62


    Object oriented programming

    JTextArea….

    63


    Object oriented programming

    JTextArea….

    JTextAreaConstructors

    JTextArea(int rows, int columns)

    Creates a text area with the specified number of rows and columns.

    JTextArea(String s, int rows, int columns)

    Creates a text area with the initial text andthe number of rows and columns specified.

    64


    Object oriented programming

    JTextArea….

    JTextArea Properties:

    • text

    • editable

    • columns

    • lineWrap

    • wrapStyleWord

    • rows

    • lineCount

    • tabSize

    65


    Object oriented programming

    Text Area

    Effect of Scroll Pane

    JTextArea

    JTextArea textArea = new JTextArea(20, 20);

    JScrollPane scrollPane = new JScrollPane(textArea);

    textArea.setEditable(true);

    JPanel p = new JPanel();

    p.add(scrollPane);


    Object oriented programming

    JTextArea…


    Object oriented programming

    JCheckBox

    • JCheckBox is a widget that has two states. On and Off. It is a box with a label.

    • If the checkbox is checked, it is represented by a tick in a box.

    • JCheckBox inherits all the properties from AbstractButtonsuch as:

      text, icon, mnemonic, verticalAlignment, horizontalAlignment, horizontalTextPosition, verticalTextPosition, and selected.

    • Provides several constructors to create check boxes.

    68


    Object oriented programming

    JCheckBox …

    69


    Object oriented programming

    JCheckBox …


    Object oriented programming

    JCheckBox …

    JCheckBox Constructor Summary

    JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected.

    JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon.

    JCheckBox(String text, Icon icon, boolean selected)

    Creates a check box with text and icon, and specifies whether or not it is initially selected.


    Object oriented programming

    JCheckBox…

    • JCheckBox red = new JCheckBox(“Red”, true);

    • JCheckBox blue = new JCheckBox(“Blue”);

    • JCheckBox green = new JCheckBox(“Green”);

    • JCheckBox yellow = new JCheckBox(“Yellow”);


    Object oriented programming

    JRadioButton

    Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

    73


    Object oriented programming

    JRadioButton

    74


    Object oriented programming

    JRadioButton

    • JRadioButton bird = new JRadioButton("Bird");JRadioButton cat = new JRadioButton("Cat");JRadioButton dog = new JRadioButton("Dog");

    • add(bird);

    • add(cat);

    • add(dog);


    Object oriented programming

    JRadioButton…

    • JRadioButton bird = new JRadioButton("Bird");JRadioButton cat = new JRadioButton("Cat");JRadioButton dog = new JRadioButton("Dog");

    • add(bird); add(cat); add(dog);

    • ButtonGroup bg = new ButtonGroup();bg.add(bird); bg.add(cat); bg.add(dog);


    Object oriented programming

    JList

    A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.

    77


    Object oriented programming

    JList…

    78


    Jlist constructors

    JList…

    JListConstructors

    • JList():Creates an empty list.

    • JList(Object[] stringItems)

      Creates a new list initialized with items.

    79


    Jlist methods

    JList…

    JlistMethods

    void setSelectionMode(intselectionMode)

    • Determines whether single-item or multiple-item selections are allowed.

      selectionMode:- is one of the three values (SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION).

      intgetSelectionMode()

    • Returns whether single-item or multiple-item selections are allowed.

    80


    Jlist methods1

    JList…

    JlistMethods

    Object[] getSelectedValues()

    •  Returns an array of the values for the selected cells.  

       Object getSelectedValue()

    • Returns the first selected value, or null if the selection is empty.

      void setListData(Object[ ]  listData)

  • Constructs a ListModel from an array of objects and then applies setModel to it.

  • 81


    Jlist methods2

    JList…

    JlistMethods

    Color getSelectionBackground()

    • Returns the background color for selected cells.

      Color getSelectionForeground()

    • Returns the selection foreground color.

      void setSelectionBackground(Color selectionBackground)

    • Sets the background color for selected cells.  

      void setSelectionForeground(Color selectionForeground)

    • Sets the foreground color for selected cells.

      intgetSelectedIndex()

  • Returns the first selected index; returns -1 if there is no selected item.

  • 82


    Jlist properties

    JList…

    JListProperties

    • selectedIndexd

    • selectedIndices

    • selectedValue

    • selectedValues

    • selectionMode

    • visibleRowCount

    83


    Object oriented programming

    Jlist…

    • String[] str={“Math”,”Computer”,”Physics”,”Chemistry”};

    • JList list = newJList(str);

    • JPanel p = new JPanel();

    • p.add(list);


    Object oriented programming

    JComboBox

    A combo boxis a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value.

    85


    Jcombobox methods

    JComboBox….

    JComboBoxMethods

    void addItem(Object  AnObject)

    • Adds an item to the item list.

      Object getItemAt(int index)

    • Returns the list item at the specified index.

      int getItemCount()

    • Returns the number of items in the list.

      int getSelectedIndex()

    • Returns the first item in the list that matches the given item.

    86


    Jcombobox methods1

    JComboBox….

    JComboBoxMethods

    Object getSelectedItem()

    • Returns the current selected item.

      void removeAllItems()

    • Removes all items from the item list.

      void removeItem(Object anObject)

    • Removes an item from the item list.

      void removeItemAt(intanIndex)

    • Removes the item at anIndex This method works only if the JComboBox uses a mutable data model.

      void setEnabled(boolean b)

    • Enables the combo box so that items can be selected.

    87


    Object oriented programming

    JComboBox….

    String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

    //Create the combo box, select item at index 4.

    //Indices start at 0, so 4 specifies the pig.

    JComboBox petList = new JComboBox(petStrings);

    petList.setSelectedIndex(4);

    88


    Object oriented programming

    Menu Components


    Object oriented programming

    Menu Components…

    import java.awt.*;import javax.swing.*;public classMainClass {public static voidmain(String args[]) {JFrame f = new JFrame("JMenuBar Sample");

    f.setSize(300, 200);f.setVisible(true);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JMenuBar bar = new JMenuBar();JMenu menu = new JMenu("Sample Menu");   /JMenuItem menuItem1=new JMenuItem(“Sub Menu 1”);menu.add(menuItem1); JMenuItem menuIte2 = new JMenuItem(“Sub Menu 2”);menu.add(menuItem2); JMenuItem menuItem3 = new JMenuItem(“Sub Menu 3”);menu.add(menuItem3);bar.add(menu);f.setJMenuBar(bar);}}


    Object oriented programming

    Adding Components into a Frame

    • Each JFrame contains a content pane.

    • A content pane is an instance of java.awt.Container.

    • The GUI components such as buttons are placed in the content pane in a frame.

    • Prior to JDK 1.5, you have to use the getContentPane() method in the JFrame class to return the content pane of the frame, and then invoke the content pane’s add method to place a component into a content pane.


    Object oriented programming

    Adding Components into a Frame

    • This was cumbersome, JDK 1.5 allows you to place the components to the content pane by invoking a frame’s add method.

    • This new feature is called content pane delegation.

    • Strictly speaking, a component is added into the content pane of the frame. But for simplicity we say that a component is added to a frame.

    • When a component is added to a container, a reference to the component is added to the list of components in the container.


    Object oriented programming

    Adding Components into a Frame

    // Add a button into the frame

    Jbutton jbt = new Jbutton(“OK”);

    frame.getContentPane().add(jbt);

    OR

    frame.getContentPane().add(new JButton("OK"));

    Title bar

    Content pane

    93


    Content pane delegation in jdk 1 5

    Adding Components into a Frame

    Content Pane Delegation in JDK 1.5

    // Add a button into the frame

    Jbutton jbt = new Jbutton(“OK”);

    frame.getContentPane().add(jbt);

    OR

    frame.getContentPane().add(new JButton("OK"));

    Title bar

    Content pane

    // Add a button into the frame

    JButton jbt = new Jbutton(“OK”)

    frame.add(jbt);

    OR

    frame.add(new JButton("OK"));

    94


    Object oriented programming

    Adding Components into a Frame

    import javax.swing.*;

    public class MyFrameWithComponents {

    public static void main(String[] args) {

    JFrame frame = new JFrame("MyFrameWithComponents");

    // Add a button into the frame

    JButton jbtOK = new JButton("OK");

    frame.add(jbtOK);

    frame.setSize(400, 300);

    frame.setVisible(true);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLocationRelativeTo(null); // New since JDK 1.4

    }

    }


    Object oriented programming

    Adding Components into a Frame

    • The add(component c) method defined in the container class adds an instance of component.

    • To remove a component from a container, use the remove(component c) method.

    • The following statements removes the button from the container.

      Example: frame.remove(jbtOK);


    Object oriented programming

    Adding Components into a Frame

    • When you run the above program MyFrameWithComponents, the button is always centered in the frame and occupies the entire frame no matter how you resize it.

    • This is because components are put in the frame by the content pane’s layout manager, and the default layout manager for the content pane places the button in the center.

    • Set layout Manager before adding components.

    • In the next section, you will use several different layout managers to place components in other location as desired.


    Object oriented programming

    Layout Management

    • Layouts tell Java where to put componentsin containers (JPanel, content pane, etc).

    • Layout manager is created using layout manager class.

    • Every layout manager class implements the LayoutManager class.

    • Each layout manager has a different style of positioning components. If you don't specify otherwise, the container will use a default layout manager.

    • Every panel(and other container) has a default layout, but it's better to set the layout explicitly for clarity.


    Object oriented programming

    Layout Management

    • Layout managers are set in containers using the setLayout(LayoutManager)method.

      Example:

      LayoutManager layoutManager = new XLayout();

      container.setLayout(layoutManager);

    • Java supplies several layout managers:these are


    Object oriented programming

    Layout Management…

    FlowLayout

    GridLayout

    null

    none, programmer sets x,y,w,h

    Left to right,

    Top to bottom

    GridBagLayout

    BorderLayout

    CardLayout

    c

    One at a time

    JButton

    w

    e


    Object oriented programming

    FlowLayout

    • Simplest layout manager.

    • Components are placed left to right in the order in which they were added. When one row is filled, a new row is started.

    • Components can be right aligned, centered or left aligned by using FlowLayout.RIGHT, FlowLayout.CENTER, and FlowLayout.LEFT respectivley.

    The FlowLayout manager is part of the java.awt package.


    The constructors flowlayout class

    FlowLayout Class

    The constructorsFlowLayoutclass

    102


    Object oriented programming

    FlowLayout

    import javax.swing.*;

    import java.awt.*;

    public class ShowFlowLayout extends JFrame {

    public ShowFlowLayout() {

    // Set FlowLayout, aligned left with horizontal gap 10

    // and vertical gap 20 between components

    setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

    // Add labels and text fields to the frame

    add(new JLabel("First Name"));

    add(new JTextField(8));

    add(new JLabel("MI"));

    add(new JTextField(1));

    add(new JLabel("Last Name"));

    add(new JTextField(8));

    }


    Object oriented programming

    FlowLayout

    public static void main(String[] args) {

    ShowFlowLayout frame = new ShowFlowLayout();

    frame.setTitle("ShowFlowLayout");

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(300, 200);

    frame.setVisible(true);

    }

    }


    Object oriented programming

    BorderLayout

    • The BorderLayout manager divides the window into five areas: East, South, West, North, and Center.

    • At most five components can be added.

    • If you want more components, add a Panel, then add components to it.

    • Components are added to a BorderLayout by using add(Component, index) where index is a constant such as :

      • BorderLayout.EAST

      • BorderLayout.SOUTH

      • BorderLayout.WEST

      • BorderLayout.NORTH

      • BorderLayout.CENTER


    Object oriented programming

    BorderLayout…

    106


    Object oriented programming

    BorderLayout …

    import javax.swing.*;

    import java.awt.BorderLayout;

    public class ShowFlowLayout extends JFrame {

    public ShowFlowLayout() {

    // Set BorderLayout with horizontal gap 5 and vertical gap 10

    setLayout(new BorderLayout(5, 10));

    // Add buttons to the frame

    add(new JButton("East"), BorderLayout.EAST);

    add(new JButton("South"), BorderLayout.SOUTH);

    add(new JButton("West"), BorderLayout.WEST);

    add(new JButton("North"), BorderLayout.NORTH);

    add(new JButton("Center"), BorderLayout.CENTER);

    }


    Object oriented programming

    BorderLayout…

    public static void main(String[] args) {

    ShowFlowLayout frame = new ShowFlowLayout();

    frame.setTitle("ShowBorderLayout");

    frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(300, 200);

    frame.setVisible(true);

    }

    }


    Object oriented programming

    GridLayout

    • The GridLayout manager divides the container up into a given number of rows and columns:

      new GridLayout(rows, columns)

    • All sections of the grid are equally sized and as large as possible

      setLayout(new GridLayout(2, 3));

      add(new Button(“one"));

      add(new Button(“two"));

      add(new Button(“three"));

      add(new Button(“four"));

      add(new Button(“five"));

      add(new Button(“six"));


    Object oriented programming

    GridLayout…

    110


    Object oriented programming

    GridLayout … example

    import javax.swing.*;

    import java.awt.GridLayout;

    public class ShowGridLayoutextends JFrame {

    publicShowGridLayout() {

    setLayout(new GridLayout(3, 2, 5, 5));

    add(new JLabel("First Name"));

    add(new JTextField(8));

    add(new JLabel("MI"));

    add(new JTextField(1));

    add(new JLabel("Last Name"));

    add(new JTextField(8));

    }


    Object oriented programming

    GridLayout example…

    public static void main(String[] args) {

    ShowGridLayout frame = new ShowGridLayout();

    frame.setTitle("ShowGridLayout");

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(200, 125); frame.setVisible(true);

    }

    }

    Output:


    Object oriented programming

    GridLayout …

    • You can specify the number of rows and columns in the grid.

    • The basic rules are as follows:

    • The number of rows or the number of columns can be zero. But not both. If one is zero and the other is nonzero, nonzero dimension is fixed, while the zero dimension is determined dynamically by the layout manager.

      For example: if you specify three rows and zero columns for a grid that has ten components, GrideLayoutcreats three fixed rows of four columns, with the last row contains two components.


    Object oriented programming

    GridLayout …

    • If both the number of rows and the number of columns are nonzero, the number of rows is the dominating parameter; that is, the number of rows is fixed, and the layout manager dynamically calculates the number of columns.

      For example: if you specify three rows and three columns for a grid that has ten components , GridLayout creates three fixed rows of four columns, with the last row containing two components.


    Object oriented programming

    GridBagLayout

    • GridBagLayout lays out components based on a grid with rows and columns that need not all be the same size.

    • GridBagLayout is the most sophisticated, flexible layout manager the Java platform provides.

    • For each component there are eleven constraint values


    Object oriented programming

    BoxLayout

    • BoxLayoutarranges components either horizontally or vertically in a panel.

    • You can control alignment and spacing of the components.

    • Complicated layouts can be made by combining many panels, some with horizontal layout and some with vertical layouts.


    Object oriented programming

    Using Panels as Sub container

    • When the user resizes the frame the layout of components can change drastically.

    • FlowLayout does not keep related items together. It just puts them in the rows one after another as they are added.

    • This section discusses how to better control the layout process.

    • One method for ensuring that a graphical interface looks the way you intend is setResizable method of JFrame. So that you can prevent the user from resizing it.

      public void setResizable(boolean resizable)


    Object oriented programming

    Using Panels as Sub container

    • If the parameter is false then the user cannot resize the frame.

    • But this does not solve all problems. When a frame contains several logical groups of components it may be difficult to lay them out correctly using a single layout manager.

    • You would like to group related components together, and then to lay out the groups in the frame. This is where panels are useful.


    Object oriented programming

    Using Panels as Sub container

    • A JPanel is a container that is used to group components together.

    • Panels do not have visible edges.

    • To layout components using JPanels:

      • Decide on how to divide the frame into panels.

      • Add GUI components to panels .

      • Add the panels to the frame.

    • Each panel has its own layout manager.


    Object oriented programming

    Using Panels as Sub container

    • The default layout manager of JPanel is Flowlayout, which is often ideal, but you may use another layout manager if appropriate.

    • When the panels are added to a frame, the frame's layout manager arranges the panels as if each panel were a single component.


    Object oriented programming

    Adding Components to JPanels

    • You can use new JPanel() to create a panel with the default FlowLayout manager or new JPanel(LayoutManager) to create a panel with the specified layout manager.

    • Use the Add(Component c) method to add a component to the panel.

    • You need to say which container (which panel) gets each component.

      Syntax: whichPanel.add(ComponentObjectRefVar);

    • means run the add() method of whichPanel to add the object to that panel.


    Object oriented programming

    Adding Components to JPanels

    For example:- The following code creates a panel and adds a button to it.

    JPanel p = new JPanel();

    p.add(new JbButton(“OK”));

    • Panels can be placed inside a frame or inside another panel.

      JFrame f = new JFrame();

      JPanel p = new JPanel();

      f.add(p);

      JPanel p1 = new JPanel();

      JPanel p = new JPanel();

      p1.add(p);

      f.add(p1);


    Object oriented programming

    Adding Components to JPanels

    • The default layout manager, for JPanel is FlowLayout, so setLayout() does not need to be called.

      Example 1: Create a window which looks like the following:


    Object oriented programming

    Adding Components to JPanels

    Create Components

    JLabel lb1 = new JLabel("Percent of Calories from Fat");

    Jlabel lbl2 = new JLabel("Enter grams of fat: ");

    Jlabel lbl3 = new JLabel("Enter total calories: ");

    Jlabel lbl4 = new JLabel("Percent calories from fat: ");

    JTextField txt1 = new JTextField( 7 );

    JTextField txt2 = new JTextField( 7 );

    JTextField txt3 = new JTextField( 7 );

    JButton jbt1 = new JButton("Do It!");


    Object oriented programming

    Adding Components to JPanels

    Create Panels

    JPanel p1 = new JPanel();

    JPanel p2 = new JPanel();

    Jpanel p3 = new JPanel();

    JPanel p4 = new JPanel();

    JPanel p5 = new JPanel();


    Object oriented programming

    Adding Components to JPanels

    Add Components to Panel

    p1.add( lb1 );

    p2.add( lbl2 );

    p2.add( txt1 );

    p3.add( lbl3 );

    p3.add( txt2 );

    p4.add( lbl4 );

    p4.add( txt3);

    p5.add( jbt1 );


    Object oriented programming

    Adding Components to JPanels

    Add Panel into the Frame

    setLayout( new FlowLayout());

    add( p1 );

    add( p2 );

    add( p3 );

    add( p4 );

    add( p5 );


    Object oriented programming

    Adding Components to JPanels

    Example 2: Create a window which looks like the following:


    Object oriented programming

    Adding Components to JPanels

    Create Components

    JLabel lData1 = new JLabel("Data Item 1");

    JLabel lData2 = new JLabel("Data Item 2");

    JLabel lData3 = new JLabel("Data Item 3");

    JTextField txData1 = new JTextField( 7 );

    JTextField txData2 = new JTextField( 7 );

    JTextField txData3 = newJTextField( 7 );


    Object oriented programming

    Adding Components to JPanels

    Create Panels

    JPanel panel1 = new JPanel();

    JPanel panel2 = new JPanel();

    JPanel panel3 = new JPanel();


    Object oriented programming

    Adding Components to JPanels

    Add Components to Panel

    panel1.add( lData1 );

    panel1.add( txData1 );

    panel2.add( lData2 );

    panel2.add( txData2 );

    panel3.add( lData3 );

    panel3.add( txData3 );


    Object oriented programming

    Adding Components to JPanels

    Add Panel into the Frame

    setLayout( new FlowLayout());

    add( panel1 );

    add( panel2 );

    add( panel3 );


    Object oriented programming

    Adding Components to JPanels

    Exercise : Create a window which looks like the following:


    Object oriented programming

    Adding Components to JPanels

    BoxLayout

    • Sometimes you want components to be lined up in a strictlyvertical (or strictly horizontal) order. This can be done with a BoxLayout layout manager.

    • Here is a constructor for it:

      BoxLayout(Container contain, int axis)

      contain: the container this layout manager is for

      axis: BoxLayout.X_AXIS — for left to right alignment

      BoxLayout.Y_AXIS — for top to bottom alignment


    Object oriented programming

    Adding Components to JPanels

    • Notice that the constructor needs a reference to the container that it is managing.

    • To set the layout manager of a JPanel to BoxLayout with vertical alignment, do this:

      JPanel panel = new JPanel();

      panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS) );


    Object oriented programming

    Adding Components to JPanels

    Example 1 : Create a window which looks like the following:


    Object oriented programming

    Adding Components to JPanels

    • Add components into the panel

      panel1.add( lData1 ); panel1.add( txData1 );

      panel2.add( lData2 ); panel2.add( txData2 );

      panel3.add( lData3 ); panel3.add( txData3 );

      panel4.add( lData4 ); panel4.add( txData4 );

      panel5.add( lData5 ); panel5.add( txData5 );

      panel6.add( lData6 ); panel6.add( txData6 );


    Object oriented programming

    Adding Components to JPanels

    • Set layout manager for left panel, add three small panels to it:

      pnLeft.setLayout( new BoxLayout( pnLeft, BoxLayout.Y_AXIS ) );

      pnLeft.add ( panel1 );

      pnLeft.add( panel2 );

      pnLeft.add ( panel3 );


    Object oriented programming

    Adding Components to JPanels

    • Set layout manager for right panel, add three small panels to it:

      pnRight.setLayout( new BoxLayout( pnRight, BoxLayout.Y_AXIS ) );

      pnRight.add( panel4);

      pnRight.add( panel5);

      pnRight.add( panel6);


    Object oriented programming

    Adding Components to JPanels

    • Add left and right panels to the frame

      setLayout( new FlowLayout() );

      add( pnLeft );

      add( pnRight );


    Object oriented programming

    Example

    • Layout Managers can be used together

      import java.awt.*;

      import javax.swing.*;

      public class TestPanels extends JFrame {

      public TestPanels() {

      JPanel p1 = new JPanel();

      p1.setLayout(newGridLayout(4, 3));

      for (int i = 1; i <= 9; i++)

      p1.add(new JButton("" + i));

      p1.add(newJButton("" + 0));

      p1.add(newJButton("Start"));

      p1.add(newJButton("Stop"));

      JPanel p2 = new JPanel(newBorderLayout());

      p2.add(newJTextField("Time to be displayed here"), BorderLayout.NORTH);


    Object oriented programming

    Example

    p2.add(p1, BorderLayout.CENTER);

    add(p2, BorderLayout.EAST);

    add(new JButton("Food to be placed here"), BorderLayout.CENTER);

    }

    public static void main(String[] args) {

    TestPanels frame = new TestPanels();

    frame.setTitle("The Front View of a Microwave Oven");

    frame.setLocationRelativeTo(null); // Center the frame

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(400, 250);

    frame.setVisible(true);

    }

    }


    Object oriented programming

    Jpanel…

    import java.awt.*;

    import javax.swing.*;

    public class MainClass extends JFrame {

    private JPanelbuttonJPanel; // panel to hold buttons

    private JButton buttons[]; // array of buttons

    public MainClass(){ // no-argument constructor

    super( "Panel Demo" );

    buttons = new JButton[ 5 ]; // create buttons array

    buttonJPanel = new JPanel(); // set up panel

    buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) );

    for (int i=0;i<buttons.length;i++){

    buttons[i] = new JButton("Button "+(i+1));

    buttonJPanel.add( buttons[i]);

    add( buttonJPanel, BorderLayout.SOUTH );

    } // end PanelFrame constructor

    } // end class PanelFrame

    }


    Object oriented programming

    JPanel…

    class PanelDemo extends JFrame {

    public static void main( String args[] ){

    MainClass panelFrame = new MainClass();

    panelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    panelFrame.setSize( 450, 200 ); // set frame size

    panelFrame.setVisible( true ); // display frame

    }

    }


    Object oriented programming

    Reading Assignment

    Constructors and Methods of all components and Layout Managers discussed in this lecture


  • Login