1 / 42

GUI Component Library

GUI Component Library. Objectives. Buttons CheckBox RadioButton List Text fields Menu and Menu Components Dialogs and File Dialogs. Swing Components. Swing defines a number of UI components These components can be used to capture data or issue commands

radha
Download Presentation

GUI Component Library

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. GUI Component Library

  2. Objectives • Buttons • CheckBox • RadioButton • List • Text fields • Menu and Menu Components • Dialogs and File Dialogs

  3. Swing Components • Swing defines a number of UI components • These components can be used to capture data or issue commands • Some of the more common components are • Buttons • Check Boxes - or toggles • Radio Buttons - same as check boxes, but are grouped together • Lists • Text fields • Menus and its subcomponents • Dialogs • File Dialog

  4. Swing Components • Most of the components discussed in this module are light weight components • They need to be added on to a container such as a JFrame or JPanel • We can use action events for many of them • Where appropriate, we refer to other type of event handlers • For each component type included in this module, we show how a component is instantiated, how it is added to a container and where appropriate, how an event handler is registered for the component

  5. Swing components and AWT • Swing components are generally thought of as JComponents. • AWT components are non-J components

  6. Inheritance hierarchy of UI Components • All JComponents included in this module are derived from the javax.swing.JComponent class (hence the name JComponents) • JComponent is itself a subclass of java.awt.Container • This hierarchy needs to be remembered while searching for methods that apply to these components since the method may be inherited • Non-J UI components derive from java.awt.Component. Thus, most discussion in this module apply to corresponding awt UI components

  7. JButtons • We have seen JButton Constructors in previous modules and have used them in various example programs • We have also seen how we can register action listeners with buttons as well as monitor for button events private JButton btn; private ImageIcon im = new ImageIcon("banana.gif"); private String lbl = "Banana”; btn = new JButton(lbl, im); btn.addActionListener(this); btn.setActionCommand(”banana"); The command string banana can then be used to find the event source

  8. Check Boxes • JCheckBox implements check boxes in Swing • Check boxes provide a toggle capability and can be used to indicate yes/no type of data items • The state of selection can be monitored through ItemListener interface. • There are 7 constructors in this class that gives the user an option to instantiate check box objects with Text and Icon labels. Initial state of the boxes can be set to selected or not-selected through the constructor • CheckBoxes can be monitored using ItemListener and ActionListener interfaces

  9. Instantiating Check Boxes JCheckBox one, two; // declare two checkboxes ..... one = new JCheckBox("One",false); //not selected to start with one.addItemListener(this); // register listener cp.add(one,BorderLayout.NORTH); // add to the container two = new JCheckBox("two",true); two.addItemListener(this); cp.add(two,BorderLayout.SOUTH); • ItemEvent has exactly one method: itemStateChanged • Using ItemEvent, we can check for the selection state of a check box; getText() method gives us the name of the check box itself

  10. ItemEvent with a Check Box public void itemStateChanged(ItemEvent e) { JCheckBox s = (JCheckBox) e.getSource(); String cblbl = s.getText(); if (cblbl.equals("one") && e.getStateChange() == ItemEvent.SELECTED) { System.out.println("Checkbox "+cblbl+" selected"); } else { if (cblbl.equals("two")) { if (e.getStateChange() == ItemEvent.SELECTED) jl.setIcon(middle); else jl.setIcon(bullet); } } } Complete code in CheckBoxTest.java getSource returns the component that triggered the event; getText returns the label of the checkbox; SELECTED constant allows us to verify whether the checkbox is selected or not

  11. Radio Buttons • Radio Buttons are new in Swing; does not exits in AWT • Just like Check Boxes, Radio Buttons are toggles • Radio Buttons are employed in a group and only one button from the group can be selected at any time • Groups of Radio Buttons are created using a container object of type ButtonGroup • Radio Buttons can be monitored through more than one listener including ItemListener and ActionListener • Radio Buttons can be instantiated with string , icon or combination of string and icon labels • There are 7 different constructors

  12. Using Radio Buttons • Instantiate a button group ButtonGroup cbg = new ButtonGroup(); • Instantiate radio buttons JRadioButton one = new JRadioButton("One",true); JRadioButton two = new JRadioButton(”Two",false); • Add buttons to the button group cbg.add(one); cbg.add(two); • Register appropriate listeners with each Radio Button one.addItemListener(this); • Write event handers

  13. Event Handling: Radio Buttons public void itemStateChanged(ItemEvent e) { JRadioButton s = (JRadioButton) e.getSource(); String st = s.getText(); if (e.getStateChange() == ItemEvent.SELECTED) { if (st.equals("One")){ jl.setIcon(ban); jl.setText("Button one clicked"); System.out.println("RadioButton "+st+" selected"); } else{ jl.setIcon(canta); jl.setText("Button two clicked"); } } } Events originate from two different buttons; label icon is changed as a response. Full code in RadioButtonTest.java

  14. Lists • Lists are components that allow the user to select one or more items from a list • Lists are implemented using JList class in Swing • A JList is used as a data entry UI component where the user can be presented with a predefined list of choices, the user may choose one or many • The selectable items in a list are elements of an Object array and remain displayed on the GUI interface • A List can be made scrollable by placing it inside a JScrollPane or SrollPane

  15. Selecting from a JList • If the user is allowed to choose only one item, it is a case of Single Selection Model; otherwise it is a multiple selection model; multiple selection can be in a single contiguous group or multiple groups • JList has 4 constructors • Instantiating a JList object String [] items = {"Mercury","Venus","Earth","Mars", "Jupiter","Saturn","Neptune" }; JList lst = new JList(items); • Since one or more items can be selected, we specify a selection model. However, by default it is single selection lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

  16. JList Event Handler • A number of event handlers can be registered with a list. • We use the ListSelectionListener which is called every time the value of selection changes lst.addListSelectionListener(this); • We can use getSelectedIndex() method of the list object to determine the selected item • ListSelection events are also fired when the selection is in the process of changing • If we are interested in the changing process, we can use the getValueIsAdjusting() method of the ListSelection event

  17. JList Event Handler public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { JList lst = (JList)e.getSource(); int firstIndex = lst.getSelectedIndex(); if (lst.isSelectionEmpty()) jl.setText("No list selection"); else jl.setText(items[firstIndex]+" selected"); } } We delay responding to an event until the selection value has completed changing Selected item is used to display a message using the JLabel. Complete example is in ListTest.java

  18. Text Field • Text Fields are created with the JTextField class • JTextField is a light weight component that allows the editing of a single line of text • We have already seen usage of text fields in previous examples; here we look at the essential code required for creating and using a text field object • There are 5 constructors of JTextField • These constructors can be used to instantiate a text field object with an initial text and / or a column size • If the column size is used, think of the size as a display window for the text, and not a limit to the number of text characters that can be entered into a text field

  19. Instantiating a Text Field • Constructing text field object JTextField tf = new JTextField(“Hello”); JTextField tf = new JTextField(30); JTextField tf = new JTextField(“Hello”,30); • Inserting a string in a text field tf.setText(“New text”); • Getting the text from a text field String s = tf.getText(); • Action events can be monitored from a text field and setActionCommand can be used to set a command string • TextListener can be used to monitor changes in the text field

  20. Menu • Menu systems are special in Java; they get added to the frame itself • The JMenuBar defines the highest level component in a menu system and provides a container for menus in the menu system • JMenus are the basic selectable menus that can be added to the menu bar, or other JMenu • Selection of a JMenu results in a drop-down list that can contain JMenu or JMenuItem objects • ActionEvent listener can be registered with menu items

  21. JMenuBar • JMenuBar is the top level horizontal object in a menu system • Creating a menu bar object JMenuBar mb = new JMenuBar(); • The menu bar needs a special method to be declared as the top level menu jf.setJMenuBar(mb); //jf is a JFrame object

  22. JMenu • JMenu is added to a JMenuBar or another JMenu • JMenu is the anchor to a drop-down menu item list • Creating a menu JMenu mFile = new JMenu("File"); JMenu option = new JMenu(”Option"); • The menu can be added to a menu bar mb.add(mFile); //mb is the menu bar • A menu can be added to another menu mFile.add(option); • A JSeparator object can be used create a horizontal separator among menus

  23. JMenuItem • JMenuItem is added to a JMenu • A JMenuItem object can be created with a text label, an icon label, or a combination of text and icon • Creating a menu item JMenuItem miOpen = new JMenuItem("Open"); • A menu item is added to a menu mFile.add(miOpen); //mFile is a menu • Event handlers are registered with menu items miOpen.addActionListener(handler); • Any number of menu items can be added to a menu • We look at an example next: BasicMenu.java

  24. Menu System Example: BasicMenu.java JMenu JMenubar JMenuItem

  25. Example: BasicMenu.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BasicMenu extends JFrame implements ActionListener { private Container cp; private JMenuBar mb; private JMenu mFile, mEdit, mHelp; private JMenuItem miOpen, miDisplay, miQuit, miList; private JMenuItem miHelp; private JLabel lbl; public static void main(String [] args) { BasicMenu mm = new BasicMenu(); }

  26. Example: BasicMenu.java public BasicMenu() { // BasicMenu.java setTitle("Mini Application Menu System"); cp = getContentPane(); setSize(500,400); lbl = new JLabel("Welcome to Menu System example"); lbl.setHorizontalAlignment(SwingConstants.CENTER); lbl.setForeground(Color.blue); lbl.setFont(new Font("Helvetica",Font.BOLD,26)); cp.add(lbl, BorderLayout.CENTER); mb = new JMenuBar(); //Menu bar mFile = new JMenu("File"); // Menus mEdit = new JMenu("Edit"); mHelp = new JMenu("Help"); mb.add(mFile); mb.add(mEdit); mb.add(mHelp);

  27. Example: BasicMenu.java miOpen = new JMenuItem("Open"); // BasicMenu.java miDisplay = new JMenuItem("Display"); miQuit = new JMenuItem("Quit"); miOpen.addActionListener(this); miDisplay.addActionListener(this); miQuit.addActionListener(this); mFile.add(miOpen); mFile.add(miDisplay); mFile.add(miQuit); miList = new JMenuItem("List"); miList.addActionListener(this); mEdit.add(miList); miHelp = new JMenuItem("Message"); miHelp.addActionListener(this); mHelp.add(miHelp);

  28. Example: BasicMenu.java setJMenuBar(mb); addWindowListener(new MyWindowAdapter()); setVisible(true); } public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand(); System.out.println("Menu item "+ac+" chosen"); } }

  29. Dialogs • Dialogs are frames that are often used as pop-up windows • Dialogs can display messages or take user’s input • They can be modal or non-modal. A user must close a modal dialog before changing the focus to some other component on the screen. Non-modal dialogs do not impose such a restriction • Dialogs can be created with Dialog class in AWT, JDialog and JOptionPane classes in Swing • Dialog and JDialog do not have any built-in controls; JOptionPane offers a limited set of built-in controls

  30. Dialogs • An AWT style dialog is built by extending java.awt.Dialog public class MyDialog extends Dialog implements ActionListener { ... } • A dialog object is created as a window within another dialog or a frame. The choice of constructor determines this. • To create a dialog within the frame of another application public MyDialog(Frame f, String title, boolean modal) { .. } • We can add controls and event handlers to a dialog frame as needed • setVisible(true) is used to display the dialog; setVisible(false) hides the dialog without releasing it from memory

  31. Dialog: Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyDialog extends Dialog implements ActionListener { private Button bOK; public MyDialog(Frame f, String title, boolean modal, String msg) { super(f,title,modal); setSize(150,200); add(new Label(msg,Label.CENTER),BorderLayout.CENTER); bOK = new Button("OK"); add(bOK,BorderLayout.SOUTH); bOK.addActionListener(this); } public void actionPerformed(ActionEvent e) { dispose(); } } MyDialog.java -called from DialogFrame.java

  32. JOptionPane • This is a Swing class that can be used to display standard dialog boxes that prompts the user for a value, or displays some information • The JOptionPane class has a large number of methods through which dialogs of various types can be constructed • For example, to show a message that informs the user of something, we can use the showMessageDialog JOptionPane.showMessageDialog(this,"Simple Dialog shown in a modal frame", "Information", JOptionPane.DEFAULT_OPTION);

  33. Dialogs using option panes are all modal, execution of the program stops until the user closes the dialog frame Parameters used in the showMessageDialog this - The supervisory frame; the dialog is displayed in this frame “Simple Dialog ...” - The message to be displayed in the dialog box “Information” - The title of the dialog box JOptionPane.DEFAULT_OPTION - Default options available in the JOptionPane class is chosen - Sets up buttons and handlers JOptionPane

  34. JFileChooser • JFileChooser is a successor of FileDialog class • JFileChooser can be used to display a file dialog MS Window 98 style file dialog: result of JFileChooser use

  35. JFileChooser • A file chooser object can be created through the FileSystemView JFileChooser fd = new JFileChooser(FileSystemView.getFileSystemView()); • The file dialog box itself is shown by calling open dialog int chrslt = fd.showOpenDialog(this); • The return value from open dialog indicates whether user selected a file (APPROVE_OPTION) or cancelled (CANCEL_OPTION) • Further file related activity can then be done using the file chooser object

  36. Dialog and FileChooser example • We show an example of creating 3 types of dialogs in DialogFrame.java • This program creates a frame and instantiates 4 buttons. • Buttons are appropriately labeled • When clicked, these buttons respond by displaying an AWT style dialog, a Swing style dialog (JOptionPane) and a file dialog (JFileChooser) • A quit button is used to exit from the demo program • MyDialog.java is used to construct the AWT style dialog

  37. Dialog and FileChooser example import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.filechooser.*; import java.io.*; public class DialogFrame extends JFrame implements ActionListener{ private Container cp; private JButton dlg, dopt, dflc; private JButton quit; public static void main(String [] args) { DialogFrame mm = new DialogFrame(); } public DialogFrame() { setTitle("Dialog chooser"); cp = getContentPane(); setSize(500,400);

  38. Dialog and FileChooser example dlg = new JButton("Dialog"); //DialogFrame.java dlg.setActionCommand("DLG"); dlg.addActionListener(this); dopt = new JButton("Option Pane"); dopt.setActionCommand("OPT"); dopt.addActionListener(this); dflc = new JButton("File Chooser"); dflc.setActionCommand("FLD"); dflc.addActionListener(this); quit = new JButton("Quit"); quit.addActionListener(this); cp.setLayout(new FlowLayout()); cp.add(dlg); cp.add(dopt); cp.add(dflc); cp.add(quit);

  39. Dialog and FileChooser example addWindowListener(new MyWindowAdapter()); //DialogFrame.java setVisible(true); } public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand(); if ("DLG".equals(ac)) { MyDialog d = new MyDialog(this, "Dialog", true, "This is a Dialog"); d.setVisible(true); } else if ("OPT".equals(ac)) { JOptionPane.showMessageDialog(this,"Simple Dialog shown in a modal frame","Information", JOptionPane.DEFAULT_OPTION); } else if ("FLD".equals(ac)) { JFileChooser fd = new JFileChooser( FileSystemView.getFileSystemView());

  40. Dialog and FileChooser example int chrslt = fd.showOpenDialog(this); //DialogFrame.java if (chrslt == JFileChooser.APPROVE_OPTION){ File f = fd.getSelectedFile(); System.out.println("File selected is "+f.getName()); } } else if ("Quit".equals(ac)) { System.exit(0); } } }

  41. Exercise • For this exercise, create an application that has a main menu bar with one menu. This menu has two menu items. When clicked, each menu item brings up a simple application as shown here • Application 1 • When button is pressed numbers in text fields are added and displayed in the last text field Text Field + Action Button

  42. Exercise • Application 2: Shows a list of gif files, when clicked the picture is displayed Display area List

More Related