Java GUI Programming Revision Tour-II Type A: Very Short Answer Questions 1 Ans: 2 Ans: 3 Ans: 4 Ans: 5 Ans: 6 Ans: 7 Ans: 8 Ans: 9 Ans: 10 Ans: 11 Ans: 12 Ans: 13 Ans: What is GUI programming? GUI stands for Graphical User Interface. A program's graphical user interface presents an easy-to-use visual display to the user. It is made up of graphical components (e.g., buttons, labels, windows). How is Swing related to GUI programming? The swing toolkit, shipped as part of java SE platform, includes a rich set of graphical components for building GUIs and adding interactivity to java applications. What is container component? A container component is a special type of component that can hold other components. Some swing containers are JPanel, JFrame etc. Name some top level containers. JFrame, JDialog, JApplet What is an event? What is event handler? Event is an occurrence of an activity. Event handler is a method that understands the event and processes it. The event handler method takes the event object as a parameter. What is layout manager? Layout manager is a way to control arrangement, position and size of visual components on a GUI form. What is the default name of action event handler of a button namely TestBin? actionPerformed()is the default name of action event handler of a button namely TestBin. Which method can programmatically mimic the click action of a push button? doClick() method can programmatically mimic the click action of a push button. What is a label used for? Label is a used for displays text and/or image that the user cannot directly change or edit. You have assigned a foreground color and background color through foreground and background properties of a label. But the label is not showing any background color. What could be the reason? If the opaque property is set to false then the label is not showing any background color. Write name of class methods to obtain and change text of a label. String getText(string) method is used for obtain text of a label. void setText(String) method is used for change text of a label. Write names of Swing API classes used to create following types of components: (i) Label (ii) dialog (iii) button (iv) text field (v) password field (vi) txt area (vii) check box (viii) radio button (ix) button group (i) JLabel (ii) JDialog (iii) JButton (iv) JTextField (v) JPasswordField (vi) JTextArea (vii) JCheckBox (viii) JRadioButton (ix) JButtonGroup Write names of most common events, event –listeners and event handler methods for the components given in previous question. 1. Events Item event Action Event CBSE CS N IP Page 1 of 9 14 Ans: 15 Ans: 16 Ans: 17 Ans: 18 Ans: 19 Ans: 20 Ans: 21 Ans: 22 Ans: 23 Ans: 24 Ans: 2. Event listeners ItemListener ActionListener 3. Event Handler Method itemStateChanged() actionPerformed() Which controls allow text entry in them? Text Field and Text Area controls are allow text entry in them. Which property would you set for setting the password character as ‘$’? We would set echoChar property for setting the password character as ‘$’. Which method returns the password entered in a password field? getPassword() method returns the password entered in a password field. Name the swing API classes that create (i) a list (ii) a combobox. (i) JList (ii) JComboBox Which list property do you set for specifying the contents of the list? selectedIndex property is used to set for specifying the contents of the list. Given a list as shown below. Write indices and positions of values: Shivansh, Gunjan, Robin, and Venkat. Venkat Rahat Mythili Shivansh Robin Kutty Gunjan Simran Salim zubin Values Indices Positions Shivansh. 3 4 Gunjan 6 7 Robin 4 5 Venkat 0 1 Which method would you use to determine which index has been selected in a list? We would use getSelectedIndices() method to determine which index has been selected in a list. How would you determine whether 7th item in a list of a list namely MyList is selected or not? Following method is used to determine whether 7th item in a list of a list namely MyList is selected or not: MyList.isSelectedIndex(7) You want to clear the selection in a list namely ChkList. How would you do this? ChkList. clearSelection() What would be the name of event handler that would handle the list selection event of a list namely WorkList? WorkList ValueChanged() How would you ensure that in a list (i) Only a single item gets selected (ii) Only a single range of items gets selected (iii) Multiple ranges of items get selected Following values of selectionMode are used to ensure that in a list (i) Only a single item gets selected - SINGLE (ii) Only a single range of items gets selected – SINGLE_INTERVAL (iii) Multiple ranges of items get selected- MULTIPLE_INTERVAL CBSE CS N IP Page 2 of 9 25 Ans: 26 Ans: 27 Ans: 28 Ans: What is a default list model? Default list model is a default implementation of list model which offers methods for manipulating list elements. Is a combo box by default editable? If not, then how you make it editable? No, by default combo box is a un editable. You can change it to be editable by setting its editable property to true i.e., checked. How would you obtain selected item from a combo box? getSelectedItem() is used to obtain selected item from a combo box. How would you determine whether a combo box is editable or not? isEditable() is used to determine whether a combo box is editable or not. Type B: Short Answer Questions 1 Ans: 2 Ans 3 Ans: Differentiate between a container and a component. container component Container is a window-like A component is an object, like a component that can contain other button or a scroll bar. components. Examples of containers are JPanel, Examples of components are JLabel, JFrame, JApplet. JTextField, JButton. Write steps to create a GUI application in java. 1. Define a container to hold components. Examples of containers are : JFrame, Jpanel, JDialog etc. 2. Add required GUI components/widgets to the container. Example of GUI components are : JButton, JLabel, JTextField etc. 3. Use Layout Manager to determine position and size of components. 4. Add action to GUI by adding event listeners to GUI components. 5. Save and test run your GUI application. Discuss briefly about different layout managers offered by Swing API. 1. Flow Layout: Default layout manager. It lays out the components from left to right 2. Border Layout: It has five areas for holding components: north, east, west, south and center. When there are only 5 elements to be placed, border layout is the right choice. 3. Grid Layout: Grid Layout places components in a grid of equally sized cells, adding them to the grid from left to right and top to bottom. 4. Grid Bag Layout: Flexible layout for placing components within a grid of cells. Allows certain components to span more than one cell. The rows of the grid are not of the same height and height. 5. Card Layout: Different components at different times are laid out. Controlled by a combo box, determining which panel the Card layout displays. 6. Box Layout: Box Layout allows multiple components to be arranged either vertically or horizontally, but not both. Components managed by Box Layout are arranged from left to right or top to bottom in the order they are added to the container. CBSE CS N IP Page 3 of 9 4 Ans: 5 Ans: 6 Ans: 7. Spring Layout: Spring Layout do their job by defining directional relationship or constraints between the edges if components. Spring Layout is very low level Layout What are top-level containers? What is their significance? The top level containers are JFrame, JDialog, JApplet. Top level containers and all its child components can be moved, hidden, shown, etc. in a single operation e.g., if you move a container then its child components also move with it; if you hide a container then all of its child controls also get hidden. Name component classes for the following GUI components. (i) Text field (ii) Text area (iii) Label (iv) Panel (v) button (i) JTextField (ii) JTextArea (iii) JLabel (iv) JPanel (v) JButton Write code for event handler of each of the buttons in following application: Button1 IntialValue Button2 Increment Button3 Decrement CalcLabel Button1 Initializes the value of label to 0 (zero) Button2 Increments the value of label by 1 (one) Button3 Decrements the value of label by 1 (one) int i=0; // Button 1 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { i=0; jLabel1.setText(Integer.toString(i)); } //Button 2 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { i=i+1; jLabel1.setText(Integer.toString(i)); } //Button 3 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { CBSE CS N IP Page 4 of 9 i=i-1; jLabel1.setText(Integer.toString(i)); 7 Ans: 8 Ans: 9 Ans: 10 Ans: } What is dispose () used for? Dispose () used for hide and dispose of the frame when the user close it. This removes the frame from the screen and frees up any resources used by it. Identify the error in following code that is written in action event handler of a button namely OKBtn. double d = nameTF.getText(); String age = ageTF.getText(); double marks = Double.parseDouble (markstf.getText()); String d = nameTF.getText(); String age = ageTF.getText(); double marks = Double.parseDouble (markstf.getText()); What is the difference between a text field and a text area? A text field’s text property can hold single line of text unless it is an HTML text. A text area’s text can hold any number of lines of text depending upon its rows property. What is the difference between a getText() and getPassword() methods? getText() Returns the text displayed by the text field. Example: String result=<text field name>.getText(); 11 Ans: 12 Ans: 13 Ans: 14 getPassword() Returns the text displayed by the password field. Example: String pass=<pass field name>.getPassword(); How can you display multiple lines of un-editable text? Through a text area we can display multiple lines of text and to make it un-editable we can set its editable property to false. What are these methods used for? (i) isEditable() (ii) setEditable() (iii) getEchoChar() (i) isEditable() -Returns the setting (true/false) whether the user can edit the text in the text area. (ii) setEditable() -Sets whether the user can edit the text in the text area. (iii) getEchoChar() -Returns the echo character. What is the significance of following properties of a text area? (i) lineWrap (ii) wrapStyleWord (i) lineWrap: Indicates whether a line of text should wrap if it is too long for the allocated width of the component. (ii) wrapStyleWord: Determines where line wrapping occurs. If true, the component attempts to wrap only at word boundaries. This property id ignored unless lineWrap is set true. What are events? What major events are associated with the following? (i) Text Field (ii) Password Field (iii) Check Box (iv) Radio Button (v) Scroll Bar (vi) Slider Do write the actions that trigger these events. CBSE CS N IP Page 5 of 9 Ans: 15 Ans: (i) Text Field: Action Event is associated with text field and triggered when user presses enter in a text field. (ii) Password Field: Action Event is associated with Password field and triggered when user presses enter in a Password field. (iii) Check Box: Item Event is associated with Check Box and triggered when a check box is clicked. (iv) Radio Button: Item Event is associated with Radio Button and triggered when a radio button is clicked. (v) Scroll Bar: Adjustment Event is associated with scroll bar and triggered when knob of a scroll bar is dragged. (vi) Slider: Change Event is associated with slider and triggered when knob of a slider is dragged. Write code for the Item event handler of a checkbox (namely incCB) that increments a variable total and displays it on a label (namely count) if the checkbox is selected. private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) { int total=5; if(jCheckBox1.isSelected()==true) { total=total+1; jLabel4.setText(Integer.toString(total)); } else { jLabel4.setText(Integer.toString(total)); } 16 Ans: 17 Ans: 18 Ans: } Write code for the event handler of a radio button so that when it is selected/unselected, its text changes to “ I am selected” or “I am unselected”). private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(jRadioButton1.isSelected()==true) { jLabel4.setText("i am selected"); } else { jLabel4.setText("i am unselected"); } } What is the significance of a button group? How do you create a button group? A button group is a group control out of which only one can be selected at a time. A button group is created through JButtonGroup component class of java Swing. In a button group we can put radio buttons or push buttons. Although checkboxes can also be put in a button group but it is not recommended. Compare and contrast a list box and a combo box. Compare List boxes and combo boxes present a list of choices to the user. CBSE CS N IP Contrast In a list, the user must select items directly from the list whereas in a combo box user can edit it if he/she whishes. List allow us to select more than one item but a combobox allows only single item selection. Page 6 of 9 19 Ans: 20 Ans: 21 Ans Write code to obtain list of selected items from a list namely List1. int ind[]=cityList.getSelectedIndices(); for(i=0;i<arrayLength;i++) What method obtain the current selection of a combo box? Give a code-example. getSelectedItem() Example private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { String dur=(String)jComboBox1.getSelectedItem(); jLabel1.setText(dur); } Discuss about some commonly used properties of lists and combo boxes. 1. Lists model : The object containing the data to be exhibited by the list. selectionMode : Describes the mode used for selecting listy items. It defines three modes of selection: SINGLE, SINGLE_INTERVAL, MULTIPLE_INTERVAL. selectedIndex : Return the index of selected item. Default is -1 i.e., initially no item is selected. If, however, yopu want a specific item to appear selected, you may set this property to a valid index. selectedIndices : Returns the indices of selected item in form an array. Default is -1 i.e., no item is by default selected. visibleRowCount : sets the preferred numbers of rows to display without requiring scrolling. 2. Combo boxes editable : if true, the user can type a new value in the text field of combo box. maximumRowCount : Defines the maximum number of rows the popup should have. model : The object containing the data to be exhibited by the combo box. selectedIndex : Returns the index of selectede item or -1 if there is none. selectedItem : Returns the selected item. TYPE C : Practical/Lab Questions 1 Design an application having interface as shown below: Textarea Ans: When the user clicks Submit button after entering data in textfields, all the entered information should be appended to text area. Recall that information can be appended to a text area using method: <textareaname>.append (“ info_to_be appended”); // SUBMIT BUTTON private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) CBSE CS N IP Page 7 of 9 { 2 Ans: // TODO add your handling code here: jTextArea1.append("Name :" + jTextField1.getText() + "\n"); jTextArea1.append("House No :" + jTextField2.getText() + "\n"); jTextArea1.append("Building :" + jTextField3.getText() + "\n"); jTextArea1.append("Street :" + jTextField4.getText() + "\n"); jTextArea1.append("City :" + jTextField5.getText() + "\n"); jTextArea1.append("State :" + jTextField6.getText() + "\n"); jTextArea1.append("info to be appended" + "\n\n") } Design a GUIapplication that displays food types in a combobox and foods pertaining to selected type in a list box. Upon selecting a specific fopod, its detail (such as calories, fat content etc.) are displayed in a separate dialog. import javax.swing.DefaultListModel; import javax.swing.JOptionPane; // combobox private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) { String str=jComboBox1.getSelectedItem().toString(); if(str.equals("Dairy")) { DefaultListModel dlm=new DefaultListModel(); dlm.addElement("Cheddar Cheese"); dlm.addElement("Processed Cheese"); dlm.addElement("Cottage Cheese"); dlm.addElement("Milk"); dlm.addElement("Curd"); dlm.addElement("Ghee"); jList1.setModel(dlm); } // same process for other food type } // ok button private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String msg=jList1.getSelectedValue().toString(); if(msg.equals("Cheddar Cheese")) { CBSE CS N IP Page 8 of 9 JOptionPane.showMessageDialog(null, "print the calories,fat etc"); } // same process for other option } // Exit Button private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: System.exit(0); } CBSE CS N IP Page 9 of 9