Creating user interfaces
1 / 51

Creating User Interfaces - PowerPoint PPT Presentation

  • Uploaded on

Creating User Interfaces. JComponent JButton JLabel JTextField JTextArea JComboBox JList JCheckBox JRadioButton Dialogs. Component Properties. The Component class is root for all UI components and containers. List of frequently used properties: font background foreground

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Creating User Interfaces' - robyn

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
Creating user interfaces
Creating User Interfaces

  • JComponent

  • JButton

  • JLabel

  • JTextField

  • JTextArea

  • JComboBox

  • JList

  • JCheckBox

  • JRadioButton

  • Dialogs

Component properties
Component Properties

The Component class is root for all UI

components and containers.

List of frequently used properties:

  • font

  • background

  • foreground

  • preferredSize

  • minimumSize

  • maximumSize

Jcomponent properties
JComponent Properties

All but a few Swing components

(such JFrame,JApplet and JDialog)

are subclasses of JComponent.

  • toolTipText

  • doubleBuffered (to reduce flickering)

  • border


A button is a component that triggers an Action Event when clicked.

The following are JButton non-default constructors:

JButton(String text)

JButton(String text, Icon icon)

JButton(Icon icon)

Jbutton properties
JButton Properties

  • mnemonic (to specify a shortcut key: Alt+S)

  • icon (image on the button)

    Position of text and icon on the button:

  • horizontalAlignment

  • verticalAlignment

  • horizontalTextPosition

  • verticalTextPosition


  • A label is a display area for a short text, an image, or both.

  • The non-default constructors for labels are as follows:

    JLabel(String text, int horizontalAlignment)

    JLabel(String text)

    JLabel(Icon icon)

    JLabel(Icon icon, int horizontalAlignment)

Jlabel methods
JLabel Methods

  • void setText(String str)

  • String getText()

  • void setAlignment(int how)




  • int getAlignment()

Jlabel methods1
JLabel Methods

  • Example:

    JLabel latLabel =

    new JLabel(”Latitude”, SwingConstants.RIGHT);


  • A text field is an input area where the usercan type in characters. Text fields are usefulin that they enable the user to enter in variable data (such as a name or a description).

Jtextfield constructors
JTextField Constructors

  • 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 thespecified text and the column size.

Jtextfield properties
JTextField Properties

  • text

  • horizontalAlignment

  • editable

  • columns

Jtextfield methods
JTextField Methods

  • String getText()

    Returns the string from the text field.

  • setText(String text)

    Puts the given string in the text field.

  • void setEditable(boolean editable)

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

  • void setColumns(int)

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

Jtextfield example
JTextField Example

  • Create JTextField

    JTextField latTextField = new JTextField("", 30);


    . . .

  • Use the JTextField

    String latString = latTextField.getText();

    // double lat = Double.parseDouble(latString);


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, which enables the user to enter multiple lines of text.

Jtextarea constructors
JTextArea Constructors

  • 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.

Jtextarea properties
JTextArea Properties

  • text

  • editable

  • columns

  • lineWrap

  • wrapStyleWord

  • rows

  • lineCount

  • tabSize

Example using text area
Example: Using Text Area

String text = “… A text …/n” + “… more text …”;

JTextArea jta = new JTextArea();



  • A combo box is 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. Also known as choice or drop-down menu

  • To create a choice, use constructors:


    JComboBox(Object[] stringItems)

Jcombobox methods
JComboBox Methods

  • To add an item to a JComboBox, use

    void addItem(Object item)

  • To get an item from JComboBox, use

    Object getItem()

Using the itemstatechanged handler
Using theitemStateChanged Handler

  • JComboBox can generate ActionEvent and ItemEvent.

  • When a choice is checked or unchecked, itemStateChanged() for ItemEvent is invoked as well as the actionPerformed() handler for ActionEvent.

Example jcombobox
Example: JComboBox

String itemString[]={”Item 1”, ”Item 2”, ”Item 3”};

// Create JComboBox

JComboBox jcbo = new JComboBox(itemsString);

// Register Listener


public void itemStateChanged(ItemEvent e)


int i = jcbo.getSelectedIndex();

//do something

System.out.println(“Index is ” + i);

System.out.println(“Item is ” + itemString[i]);



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.

Jlist constructors
JList Constructors

  • JList()

    Creates an empty list.

  • JList(Object[] stringItems)

    Creates a new list initialized with items.

Jlist properties methods
JList Properties & Methods

  • selectedIndex

  • selectedIndices

  • selectedValue

  • selectedValues

  • selectionMode: SINGLE_SELECTION,



  • int getSelectedIndex()

  • int[] getSelectedIndices()


A check box is a component that enables the user to toggle a choice on or off, like a light switch.

Jcheckbox constructors
JCheckBox Constructors

  • JCheckBox()

  • JCheckBox(String text)

  • JCheckBox(String text, boolean selected)

  • JCheckBox(Icon icon)

  • JCheckBox(String text, Icon icon)

  • JCheckBox(String text, Icon icon, boolean selected)

Jcheckbox properties
JCheckBox Properties

  • JCheckBox has all the properties in JButton.

  • Additionally, JCheckBox has the following property:



jchk1 = new JCheckBox(“Check 1”, FALSE);

jchk2 = new JCheckBox(“Check 2”, TRUE);




public void itemStateChanged(ItemEvent e) {

int i;

if(e.getSource() instanceof JCheckBox) {

if(jchk1.isSelected()) {

// do something


if(jchk2.isSelected()) {

// do something else





  • Radio buttons are variations of check boxes.

  • They are often used in the group, where onlyone button is checked at a time.

Jradiobutton constructors
JRadioButton Constructors

  • JRadioButton()

  • JRadioButton(String text)

  • JRadioButton(String text, boolean selected)

  • JRadioButton(Icon icon)

  • JRadioButton(String text, Icon icon)

  • JRadioButton(String text, Icon icon, boolean selected)

Jradiobutton properties
JRadioButton Properties

  • JRadioButton has all the properties in JButton.

  • Additionally, JRadioButton has the following property:



    JRadioButton jrb1 = JRadioButton(“Radio 1”);

    JRadioButton jrb2 = JRadioButton(“Radio 2”, selected);

Grouping radio buttons
Grouping Radio Buttons

// Create JRadioButtons

JRadioButton jrb1 = JRadioButton(“Radio 1”);

JRadioButton jrb2 = JRadioButton(“Radio 2”, selected);

// Create group of JRadioButtons

ButtonGroup jrbg = new ButtonGroup();



Message dialogs
Message Dialogs

  • A dialog is normally used as a temporary window to receive additional information from the user, or to provide notification that some event has occurred.

Creating message dialogs
Creating Message Dialogs

Use static method in JOptionPane class.

  • showMessageDialog(

    Component parentComponent,

    Object message,

    String title,

    int messageType)

  • showMessageDialog(

    Component parentComponent,

    Object message,

    String title,

    int messageType,

    Icon icon)


Example: Message dialog with default title and icon:

String str = ”Eggs are not supposed to be green.”;

JOptionPane.showMessageDialog(frame, str);



String str = ”Eggs are not supposed to be green.”;

JOptionPane.showMessageDialog(frame, str,


JOptionPane.showMessageDialog(frame, str,

“Inane warning”,



String str = ”Eggs are not supposed to be green.”;

JOptionPane.showMessageDialog(frame, str,

“Inane error”,


JOptionPane.showMessageDialog(frame, str,

“A plain message”,


Confirm dialog
Confirm Dialog

int n = JOptionPane.showConfirmDialog(frame,

"Would you like green eggs and ham?",

"An Inane Question",


Input dialog
Input Dialog

Object[] possibilities = {"ham", "spam", "yam"};

String s = (String)JOptionPane.showInputDialog(

frame, "Complete the sentence:\n” +

”\"Green eggs and...\"", "Customized Dialog",

JOptionPane.PLAIN_MESSAGE, icon, possibilities,"ham");

//If a string was returned, say so.

if ((s != null) && (s.length() > 0)) {

setLabel("Green eggs and... " + s + "!");



//If you're here, the return value was null/empty.

setLabel("Come on, finish the sentence!");

int n = JOptionPane.


  • As the previous code snippets showed, the showMessageDialog, showConfirmDialog, and showOptionDialog methods return an integer indicating the user's choice.

  • The values for this integer are YES_OPTION, NO_OPTION,CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION. Each option corresponds to the button the user pressed.

  • Exception: when CLOSED_OPTION is returned, it indicates that the user closed the dialog window explicitly, rather than by choosing a button inside the option pane.



  • A scroll pane is a component that supports automatically scrolling without coding.


  • Java provides several classes—JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, and JRadioButtonMenuItem —to implement menus in a frame.

  • A JFrame or JApplet can hold a menu bar to which the pull-down menus are attached.

  • Menus consist of menu items that the user can select (or toggle on or off). Menu bars can be viewed as a structure to support menus.

Menu demo
Menu Demo

Menu Bar

Menu Items

The jmenubar class
The JMenuBar Class

  • A menu bar holds menus; the menu bar can only be added to a frame.

  • Example: Create and add a JMenuBar to a frame:

JFrame frame = new JFrame();

frame.setSize(300, 200);


JMenuBar mb = new JMenuBar(); frame.setJMenuBar(mb);

The menu class
The Menu Class

  • Attach menus onto a JMenuBar.

  • Example: create two menus, File and Help, and add

  • them to the JMenuBar mb:

JMenu fileMenu = new JMenu("File", false);

JMenu helpMenu = new JMenu("Help", true);



The menuitem class
The MenuItem Class

  • Individual items of Menu.


    MenuItem(String ItemName)

    MenuItem(String ItemName,

    MenuShortcut keyAccel)

1 create menu items
1. Create Menu Items

JMenuItem jmiNew = new JMenuItem("new");

JMenuItem jmiOpen = new JMenuItem("open");

JMenuItem jmiPrint= new JMenuItem("print");

JMenuItem jmiExit = new JMenuItem("exit");

2 add menu items
2. Add Menu Items



fileMenu.add(new JMenuItem("-")); // separator



fileMenu.add(new JMenuItem("-")); // separator

3 register listener
3. Register Listener





4 implement handler
4. Implement Handler

public void actionPerformed(ActionEvent e) {

String actionCommand = e.getActinCommand();

if(e.getSource() isntanceof JMenuItem) {

if(“New”.equals(actionCommand)) {

// DO IT!


else if(“Open”.equals(actionCommand)) {

// DO IT!


else if(“Print”.equals(actionCommand)) {

// DO IT!


else if(“Exit”.equals(actionCommand)) {