SWING GUI COMPONENTS AND MENUS

44
SWING GUI COMPONENTS AND MENUS Presented By- Anup Kumar Das (DC2012MCA0018) Elora Das (DC2012MCA0021) Seema Roy (DC2012MCA0024) Barnali Sarma (DC2012MCA0025)

description

SWING GUI COMPONENTS AND MENUS. Presented By- Anup Kumar Das (DC2012MCA0018) Elora Das (DC2012MCA0021) Seema Roy (DC2012MCA0024) Barnali Sarma (DC2012MCA0025). Contents. Swing GUI Components: Jlabel JTextField JTextArea JButton JCheckBox JRadioButton JList JComboBox - PowerPoint PPT Presentation

Transcript of SWING GUI COMPONENTS AND MENUS

Page 1: SWING GUI COMPONENTS AND MENUS

SWING GUI COMPONENTS AND MENUS

Presented By-

Anup Kumar Das (DC2012MCA0018)Elora Das (DC2012MCA0021)Seema Roy (DC2012MCA0024)Barnali Sarma (DC2012MCA0025)

Page 2: SWING GUI COMPONENTS AND MENUS

CONTENTS Swing GUI Components:

Jlabel JTextField JTextArea JButton JCheckBox JRadioButton JList JComboBox JScrollBar JScrollPane JToolTip JPanel JFrames

Menus: JmenuBar Jmenu JMenuItem JSeparator

Page 3: SWING GUI COMPONENTS AND MENUS

BARNALI SARMA (DC2012MCA0025 )

Swing GUI Components: Jlabel JTextField JTextArea JButton JCheckBox

Page 4: SWING GUI COMPONENTS AND MENUS

Swing is the primary Java GUI widget toolkit.

It is part of Oracle's Java Foundation Classes (JFC) — for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). 

It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.

Unlike AWT components, Swing components are not implemented by platform-specific code. Instead they are written entirely in Java and therefore are platform-independent.

Introduction

Page 5: SWING GUI COMPONENTS AND MENUS

JLabel  is a subclass of Jcomponent.

• used to create text labels.

•We use a Swing JLabel when we need a user interface component that displays a message or an image.

• A JLabel object provides text instructions or information on a GUI - display a single line of read-only text, an image or both text and image.

JLabel

Page 6: SWING GUI COMPONENTS AND MENUS

JLABEL CONSTRUCTOR JLabel()

Creates a JLabel instance with no image and with an empty string for the title.

JLabel(Icon image)

Creates a JLabel instance with the specified image.

JLabel(Icon image, int horizontalAlignment)

Creates a JLabel instance with the specified image and horizontal alignment.

JLabel(String text)

Creates a JLabel instance with the specified text.

JLabel(String text, Icon icon, int horizontalAlignment

Creates a JLabel instance with the specified text, image, and horizontal alignment.

JLabel(String text, int horizontalAlignment)

Creates a JLabel instance with the specified text and horizontal alignment.

SwingConstants.LEFTSwingConstants.CENTERSwingConstants.RIGHTSwingConstants.LEADINGSwingConstants.TRAILING

Page 7: SWING GUI COMPONENTS AND MENUS

import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.ImageIcon; public class JlabelDemo extends JPanel { JLabel jlbLabel1, jlbLabel2, jlbLabel3; public JlabelDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG", "My Website"); // Creating an Icon setLayout(new GridLayout(3, 1)); // 3 rows, 1 column Panel having Grid

Layout jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER); // We can position of the text, relative to the icon: jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM); jlbLabel1.setHorizontalTextPosition(JLabel.CENTER); jlbLabel2 = new JLabel("Text Only Label"); jlbLabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlbLabel1); add(jlbLabel2); add(jlbLabel3); }

Page 8: SWING GUI COMPONENTS AND MENUS

public static void main(String[] args) { JFrame frame = new JFrame("jLabel Usage Demo"); frame.addWindowListener(new WindowAdapter() { // Shows code to Add Window Listener public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JlabelDemo()); frame.pack(); frame.setVisible(true); } } Output-

Page 9: SWING GUI COMPONENTS AND MENUS

JTextField• JTextField allows editing/displaying of a single line of text. JTextField is an input area where the user can type in characters.

• New features include the ability to justify the text left, right, or center, and to set the text’s font.

•When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the listener processes the event and can use the data in the text field at the time of the event in the program.

Page 10: SWING GUI COMPONENTS AND MENUS

JTextField Constructor

JTextField()Constructs a new TextField.

JTextField(Document doc, String text, int columns)Constructs a new JTextField that uses the given text storage model and the given number of columns.

JTextField(int columns)Constructs a new empty TextField with the specified number of columns.

JTextField(String text)Constructs a new TextField initialized with the specified text.

JTextField(String text, int columns)Constructs a new TextField initialized with the specified text and columns.

Page 11: SWING GUI COMPONENTS AND MENUS

import javax.swing.*; import java.awt.*; public class TFInFrame extends JFrame { public TFInFrame(){ super("JTextField in a JFrame"); // Use the dafault metal styled titlebar setUndecorated(true); getRootPane().setWindowDecorationStyle(JRootPane.FRAME); // Set the style of the frame add(new JTextField("I'm a JTextField", 25)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setLayout(new FlowLayout()); pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args){ new TFInFrame(); } }

Output -

Page 12: SWING GUI COMPONENTS AND MENUS

JTextArea•  JTextArea allows editing of multiple lines of text.

• JTextArea can be used in conjunction with class JScrollPane to achieve scrolling.

•The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar.

JTextArea Constructor

JTextArea()Constructs a new TextArea.

JTextArea(Document doc)Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).

Page 13: SWING GUI COMPONENTS AND MENUS

JTextArea(Document doc, String text, int rows, int columns)Constructs a new JTextArea with the specified number of rows and columns, and the given model.

JTextArea(int rows, int columns)Constructs a new empty TextArea with the specified number of rows and columns.

JTextArea(String text)Constructs a new TextArea with the specified text displayed.

JTextArea(String text, int rows, int columns)Constructs a new TextArea with the specified text and number of rows and columns.

Page 14: SWING GUI COMPONENTS AND MENUS

import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.UIManager;

public class TextAreaExample {  public static void main(String[] args) {    JFrame f = new JFrame("Text Area Examples");    JPanel upperPanel = new JPanel();    JPanel lowerPanel = new JPanel();    f.getContentPane().add(upperPanel, "North");    f.getContentPane().add(lowerPanel, "South");

    upperPanel.add(new JTextArea(content));    upperPanel.add(new JTextArea(content, 6, 10));    upperPanel.add(new JTextArea(content, 3, 8));

    lowerPanel.add(new JScrollPane(new JTextArea(content, 6, 8)));    JTextArea ta = new JTextArea(content, 6, 8);    ta.setLineWrap(true);    lowerPanel.add(new JScrollPane(ta));

    ta = new JTextArea(content, 6, 8);    ta.setLineWrap(true);    ta.setWrapStyleWord(true);    lowerPanel.add(new JScrollPane(ta));

    f.pack();    f.setVisible(true);  }

Page 15: SWING GUI COMPONENTS AND MENUS

  static String content = "Here men from the planet Earth\n"      + "first set foot upon the Moon,\n" + "July 1969, AD.\n"      + "We came in peace for all mankind.";}

Output -

Page 16: SWING GUI COMPONENTS AND MENUS

JButton•  The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including JButton.

• A button is a component the user clicks to trigger a specific action.

• There are several types of buttons in Java, all are subclasses of AbstractButton.

command buttons: is created with class JButton. It generates ActionEvent.

toggle buttons: have on/off or true/false values.

check boxes: a group of buttons. It generates ItemEvent.

radio buttons: a group of buttons in which only one can be selected. It generates ItemEvent.

Page 17: SWING GUI COMPONENTS AND MENUS

JButton Constructor

JButton()Creates a button with no set text or icon.

JButton(Action a)Creates a button where properties are taken from the Action supplied.

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 initial text and an icon.

Page 18: SWING GUI COMPONENTS AND MENUS

import java.awt.*; import javax.swing.*; class ButtonFrame extends JFrame { JButton bChange ; // reference to the button object // constructor for ButtonFrame ButtonFrame(String title) { super( title ); // invoke the JFrame constructor setLayout( new FlowLayout() ); // set the layout manager bChange = new JButton("Click Me!"); // construct a JButton add( bChange ); // add the button to the JFrame setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } public class ButtonDemo { public static void main ( String[] args ) { ButtonFrame frm = new ButtonFrame("Button Demo"); frm.setSize( 150, 75 ); frm.setVisible( true ); } }

Output -

Page 19: SWING GUI COMPONENTS AND MENUS

JCheckBox• The JCheckbox is a widget that lets you select more than one attribute at a time on the screen by 'checking' i.e. ticking selections in a list.

• This is useful when multiple choices are involved, like the people you want to play in your football team.

•Each CheckBox has a state of either selected or deselected. 

JCheckBox Constructors

JCheckBox ()Creates a blank JCheckBox instance

.JCheckBox (String Text)Creates a JCheckBox instance with the specified text

.JCheckBox (String Text, boolean Selected)Creates a JCheckBox instance with the specified text and the designated selection state.

Page 20: SWING GUI COMPONENTS AND MENUS

import javax.swing.*;

public class CreateCheckBox{  public static void main(String[] args){  JFrame frame = new JFrame("Check Box Frame");  JCheckBox chk = new JCheckBox("This is the Check Box");  frame.add(chk);  frame.setSize(400, 400);  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  frame.setVisible(true);  }}

Output -

Page 21: SWING GUI COMPONENTS AND MENUS

JRADIOBUTTON, JLIST, JCOMBOBOX, JSCROLLBAR

Seema RoyDC2012MCA0024

Page 22: SWING GUI COMPONENTS AND MENUS

JRADIOBUTTON•Radio buttons–Have two states: selected and deselected

–Normally appear as a group

•Only one radio button in group selected at time•Selecting one button forces the other buttons off–Mutually exclusive options

–ButtonGroup - maintains logical relationship between radio buttons

•Class JRadioButton–Constructor

•JRadioButton( "Label", selected )•If selected true, JRadioButton initially selected

Page 23: SWING GUI COMPONENTS AND MENUS

1. import

1.1 Declarations

1.2 Initialization

1 // Fig. 12.12: RadioButtonTest.java2 // Creating radio buttons using ButtonGroup and

JRadioButton.3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class RadioButtonTest extends JFrame {8 private JTextField t;9 private Font plainFont, boldFont,10 italicFont, boldItalicFont;11 private JRadioButton plain, bold, italic,

boldItalic;12 private ButtonGroup radioGroup;1314 public RadioButtonTest()15 {16 super( "RadioButton Test" );1718 Container c = getContentPane();19 c.setLayout( new FlowLayout() );2021 t = new JTextField( "Watch the font style

change", 25 );22 c.add( t );2324 // Create radio buttons25 plain = new JRadioButton( "Plain",

true ); 26 c.add( plain );27 bold = new JRadioButton( "Bold", false);28 c.add( bold );29 italic = new JRadioButton( "Italic",

false ); 30 c.add( italic );

Initialize radio buttons. Only one is initially selected.

Page 24: SWING GUI COMPONENTS AND MENUS

31 boldItalic = new JRadioButton( "Bold/Italic", false );32 c.add( boldItalic );

3334 // register events35 RadioButtonHandler handler = new

RadioButtonHandler();36 plain.addItemListener( handler );37 bold.addItemListener( handler );38 italic.addItemListener( handler );39 boldItalic.addItemListener( handler );4041 // create logical relationship between

JRadioButtons42 radioGroup = new ButtonGroup();43 radioGroup.add( plain );44 radioGroup.add( bold );45 radioGroup.add( italic );46 radioGroup.add( boldItalic );4748 plainFont = new Font( "TimesRoman",

Font.PLAIN, 14 );49 boldFont = new Font( "TimesRoman", Font.BOLD, 14 );50 italicFont = new Font( "TimesRoman", Font.ITALIC, 14 );51 boldItalicFont =

52 new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 );53 t.setFont( plainFont );

5455 setSize( 300, 100 );56 show();57 }58

Create a ButtonGroup. Only one radio button in the group may be selected at a time.

Method add adds radio buttons to the ButtonGroup

Page 25: SWING GUI COMPONENTS AND MENUS
Page 26: SWING GUI COMPONENTS AND MENUS

JList

The ListExample.java creates a simple list box example using the Swing API:

This example generates a static list from which the user can make a selection.

This code provides no mechanism to detect the selections made,nor does it include the capability to scroll the list -- The JList class does not provide this: use JScrollPane.

Constructor JList( arrayOfNames )Takes array of Objects (Strings) to display in list

Page 27: SWING GUI COMPONENTS AND MENUS

A Simple JListThe full code listing for this program is:// Imports import java.awt.*; import java.awt.event.*; import javax.swing.*; class ListExample extends JFrame {

// Instance attributes used in this example private JPanel topPanel; private JList listbox;

// Constructor of main frame public ListExample() { // Set the frame characteristics setTitle( "Simple ListBox Application" ); setSize( 300, 100 ); setBackground( Color.gray ); // Create a panel to hold all other components topPanel = new JPanel(); topPanel.setLayout( new BorderLayout() ); getContentPane().add( topPanel );

// Create some items to add to the list String listData[] = { "Item 1", "Item 2", "Item 3", "Item 4" };

Page 28: SWING GUI COMPONENTS AND MENUS

// Create a new listbox control listbox = new JList( listData ); topPanel.add( listbox, BorderLayout.CENTER ); } // Main entry point for this example public static void main( String args[] ) { // Create an instance of the test application ListExample mainFrame = new ListExample(); mainFrame.setVisible( true ); } }

Output

Page 29: SWING GUI COMPONENTS AND MENUS

JComboBox

A JComboBox describes a menu with several choices, one of which can be selected. When the user is not accessing the JComboBox object, only the currently selected choice (and a down arrow) appears in the menu. The class JComboBox is similar to class Choice in AWT.

Methods in JComboBox include:void addItem(Object alternative);void insertItemAt(Object alternative, int loc);void removeItem(Object alternative);void removeItemAt(int loc);Object getSelectedItem( );int getSelectedIndex( );Object getItemAt(int loc);int getItemCount( );void setEditable(boolean);

Add to end of menuMenu items may be String (text) or icons

Allows the user to input text if “true”

Page 30: SWING GUI COMPONENTS AND MENUS

A JComboBox, which lets the user choose one of several choices, can have two very different forms. The default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list. Here's what the two forms of combo boxes look like in the Java look and feel:

Uneditable combobox Editable coboboxCombobox

Page 32: SWING GUI COMPONENTS AND MENUS

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class JComboBoxDemo extends JPanel{

JLabel jlbPicture; public JComboBoxDemo(){

String[] comboTypes = { "Numbers", "Alphabets", "Symbols" };

// Create the combo box, and set 2nd item as Default JComboBox comboTypesList = new JComboBox(comboTypes);

comboTypesList.setSelectedIndex(2); comboTypesList.addActionListener(new ActionListener()

{public void actionPerformed(ActionEvent e){

JComboBox jcmbType = (JComboBox) e.getSource();

String cmbType = (String) jcmbType.getSelectedItem();

jlbPicture.setIcon(new ImageIcon("" + cmbType.trim().toLowerCase() + ".jpg"));

}}); // Set up the picture

Page 33: SWING GUI COMPONENTS AND MENUS

jlbPicture = new JLabel(new ImageIcon("" + comboTypes[comboTypesList.getSelectedIndex()] + ".jpg")); jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); jlbPicture.setPreferredSize(new Dimension(177, 122 + 10)); // Layout the demo setLayout(new BorderLayout());add(comboTypesList, BorderLayout.NORTH);add(jlbPicture, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));}public static void main(String s[]){

JFrame frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter()

{public void windowClosing(WindowEvent e){

System.exit(0);}

});frame.setContentPane(new JComboBoxDemo());frame.pack();frame.setVisible(true);

}}

Page 34: SWING GUI COMPONENTS AND MENUS

JScrollBar

•The user positions the knob in the scrollbar to determine the contents of the viewing area.

•The program typically adjusts the display so that the end of the scrollbar represents the end of the displayable contents, or 100% of the contents.

•The start of the scrollbar is the beginning of the displayable contents, or 0%. The position of the knob within those bounds then translates to the corresponding percentage of the displayable contents.

Constructor and Description

JScrollBar()Creates a vertical scrollbar with the following initial values:JScrollBar(int orientation)Creates a scrollbar with the specified orientation and the following initial values:JScrollBar(int orientation, int value, int extent, int min, int max)Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

Page 35: SWING GUI COMPONENTS AND MENUS

Swing ComponentsJScrollBar

The constructor for a JScrollBar has the following parameters

•Initial value

•Size of the indicator

•Minimum value

•Maximum value

•Orientation JScrollBar.HORIZONTAL or JScrollBar.VERTICAL

Choosing 0 sets indicator to the default size

JScrollBar scrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 10, 0, 1, 20);

Page 36: SWING GUI COMPONENTS AND MENUS

ANUP KUMAR DAS (DC2012MCA0018)Menus: JmenuBar Jmenu JMenuItem JSeparator

Page 37: SWING GUI COMPONENTS AND MENUS

WHAT IS MENU?

A menu provides a space-saving way to let the user choose one of several options. Other components with which the user can make a one-of-many choice include combo boxes , lists , radio buttons and tool bars. orA menu is a way to arrange buttons. There are several types.

TRADITIONAL DROPDOWN MENUS:

These are positioned across the top of a window in a menu bar, and displayed below the menu name.

POPUP MENUS:

These appear when the user clicks, eg with the right mouse button, on a component that can handle a popup request.

Page 38: SWING GUI COMPONENTS AND MENUS

.

JMENU:

It has a name and contains a number of menu items which are displayed in a vertical list of menu items.

JMENUBAR: It is positioned across the top of a container (eg a JFrame, JPanel, or JApplet). It's placed above the content pane, so does not use the container's layout.

JMENU ITEMS:

These are usually text "buttons", but can also have icons, checkboxes, radio buttons, or be hierarchical submenus.

Page 39: SWING GUI COMPONENTS AND MENUS

JSEPARATOR:

The JSeparator class is a special component that acts as a separator on a JMenu.

JSeparator can be used anywhere that we want to use a horizontal or vertical line to separate different areas of a screen.

The JSeparator class provides a horizontal or vertical dividing line or empty space:

Page 40: SWING GUI COMPONENTS AND MENUS

Creating and Setting Up Menu Bars:

Constructor or Method Purpose

JMenuBar() Creates a menu bar.JMenu add(JMenu) Adds the menu to the end of the menu bar.

Creating and Populating Menus:

Constructor or Method Purpose

JMenu() Creates a menu.

JMenu(String) The string specifies the text to display for the menu

JMenu(Action) The Action specifies the text and other properties of the menu

Page 41: SWING GUI COMPONENTS AND MENUS

Implementing Menu Items:

Constructor or Method Purpose

JMenuItem() Creates an ordinary menu item.

JMenuItem(String) The string argument specifies the text that the menu item should display.

Creating, Populating, and Controlling Popup Menus:

Constructor or Method Purpose

void addSeparator() Adds a separator to the current end of the popup menu.

Page 42: SWING GUI COMPONENTS AND MENUS

Program to create jmenu,jmenubar,jmenuitem and jseparator

import javax.swing.*;

public class SwingMenu{public static void main(String[] args) {

SwingMenu s = new SwingMenu();}

public SwingMenu(){JFrame frame = new JFrame("Creating a JMenuBar,

JMenu, JMenuItem and seprator Component");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JMenuBar menubar = new JMenuBar();JMenu filemenu = new JMenu("File");filemenu.add(new JSeparator());JMenu editmenu = new JMenu("Edit");editmenu.add(new JSeparator());JMenuItem fileItem1 = new JMenuItem("New");JMenuItem fileItem2 = new JMenuItem("Open");JMenuItem fileItem3 = new JMenuItem("Close");fileItem3.add(new JSeparator());

Page 43: SWING GUI COMPONENTS AND MENUS

JMenuItem fileItem4 = new JMenuItem("Save");JMenuItem editItem1 = new JMenuItem("Cut");JMenuItem editItem2 = new JMenuItem("Copy");editItem2.add(new JSeparator());JMenuItem editItem3 = new JMenuItem("Paste");JMenuItem editItem4 = new JMenuItem("Insert");filemenu.add(fileItem1);filemenu.add(fileItem2);filemenu.add(fileItem3);filemenu.add(fileItem4);editmenu.add(editItem1);editmenu.add(editItem2);editmenu.add(editItem3);editmenu.add(editItem4);menubar.add(filemenu);menubar.add(editmenu);frame.setJMenuBar(menubar);frame.setSize(400,400);frame.setVisible(true);

}}

Page 44: SWING GUI COMPONENTS AND MENUS

Output: