1 / 44

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). Contents. Swing GUI Components: Jlabel JTextField JTextArea JButton JCheckBox JRadioButton JList JComboBox

gilon
Download Presentation

SWING GUI COMPONENTS AND MENUS

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Contents Swing GUI Components: • Jlabel • JTextField • JTextArea • JButton • JCheckBox • JRadioButton • JList • JComboBox • JScrollBar • JScrollPane • JToolTip • JPanel • JFrames Menus: • JmenuBar • Jmenu • JMenuItem • JSeparator

  3. Barnali Sarma (DC2012MCA0025 ) Swing GUI Components: • Jlabel • JTextField • JTextArea • JButton • JCheckBox

  4. Introduction Swing is the primary JavaGUIwidget 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.

  5. JLabel • JLabel  is a subclass of Jcomponent. • used to create text labels. • We use a SwingJLabel 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. • .

  6. 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, inthorizontalAlignment) 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, inthorizontalAlignment Creates a JLabel instance with the specified text, image, and horizontal alignment. • JLabel(String text, inthorizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. • SwingConstants.LEFT • SwingConstants.CENTER • SwingConstants.RIGHT • SwingConstants.LEADING • SwingConstants.TRAILING

  7. 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); j lbLabel2 = new JLabel("Text Only Label"); jlbLabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlbLabel1); add(jlbLabel2); add(jlbLabel3); }

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

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

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

  11. importjavax.swing.*; import java.awt.*; publicclassTFInFrameextendsJFrame { publicTFInFrame(){ super("JTextField in a JFrame"); // Use the dafault metal styled titlebarsetUndecorated(true); getRootPane().setWindowDecorationStyle(JRootPane.FRAME); // Set the style of the frame add(newJTextField("I'm a JTextField", 25)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setLayout(newFlowLayout()); pack(); setLocationRelativeTo(null); setVisible(true); } publicstaticvoid main(String[] args){ newTFInFrame(); } } Output -

  12. JTextArea • JTextArea allows editing of multiple lines of text. • JTextArea can be used in conjunction with classJScrollPane 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).

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

  14. 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");JPanelupperPanel = new JPanel();JPanellowerPanel = 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)));JTextAreata = 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);  }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");JPanelupperPanel = new JPanel();JPanellowerPanel = 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)));JTextAreata = 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);  }

  15. 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.";}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 -

  16. JButton • The abstract class AbstractButtonextends 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.

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

  18. import java.awt.*; import javax.swing.*; class ButtonFrame extends JFrame { JButtonbChange ; // 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 ) { ButtonFramefrm = new ButtonFrame("Button Demo"); frm.setSize( 150, 75 ); frm.setVisible( true ); } } Output -

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

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

  21. JRadioButton, JList, JComboBox, JScrollBar Seema Roy DC2012MCA0024

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

  23. 1. import 1.1 Declarations 1.2 Initialization 1 // Fig. 12.12: RadioButtonTest.java 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 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; 13 14 public RadioButtonTest() 15 { 16 super( "RadioButton Test" ); 17 18 Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); Initialize radio buttons. Only one is initially selected. 20 21 t = new JTextField( "Watch the font style change", 25 ); 22 c.add( t ); 23 24 // Create radio buttons 25 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 );

  24. 31 boldItalic = new JRadioButton( "Bold/Italic", false ); 32 c.add( boldItalic ); 33 34 // register events 35 RadioButtonHandler handler = new RadioButtonHandler(); Create a ButtonGroup. Only one radio button in the group may be selected at a time. 36 plain.addItemListener( handler ); 37 bold.addItemListener( handler ); 38 italic.addItemListener( handler ); 39 boldItalic.addItemListener( handler ); 40 41 // create logical relationship between JRadioButtons 42 radioGroup = new ButtonGroup(); Method add adds radio buttons to the ButtonGroup 43 radioGroup.add( plain ); 44 radioGroup.add( bold ); 45 radioGroup.add( italic ); 46 radioGroup.add( boldItalic ); 47 48 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 ); 54 55 setSize( 300, 100 ); 56 show(); 57 } 58

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

  26. A Simple JList The 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 JPaneltopPanel; private JListlistbox; // 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" };

  27. // 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 ListExamplemainFrame = new ListExample(); mainFrame.setVisible( true ); } } Output

  28. 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: Add to end of menu 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); Menu items may be String (text) or icons Allows the user to input text if “true”

  29. 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: Combobox Uneditable combobox Editable cobobox

  30. Constructor and Description JComboBox()Creates a JComboBox with a default data model. JComboBox(ComboBoxModel<E> aModel)Creates a JComboBox that takes its items from an existing ComboBoxModel. JComboBox(E[] items)Creates a JComboBox that contains the elements in the specified array. JComboBox(Vector<E> items)Creates a JComboBox that contains the elements in the specified Vector.

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

  32. 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); } }

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

  34. Swing Components JScrollBar The constructor for a JScrollBar has the following parameters • Orientation JScrollBar.HORIZONTAL or JScrollBar.VERTICAL • Initial value • Size of the indicator Choosing 0 sets indicator to the default size • Minimum value • Maximum value JScrollBar scrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 10, 0, 1, 20);

  35. Anupkumar das (DC2012mca0018) Menus: • JmenuBar • Jmenu • JMenuItem • JSeparator

  36. 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. • or • A 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.

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

  38. 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:

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

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

  41. 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); JMenuBarmenubar = new JMenuBar(); JMenufilemenu = new JMenu("File"); filemenu.add(new JSeparator()); JMenueditmenu = 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());

  42. 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); } }

  43. Output:

More Related