Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls

Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls is part of Informatics Practices Class 12 Important Questions. Here we have given Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls.

Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls

1 Mark Questions

Question 1.
What is a button group? Which control is generally used with a button group? (Delhi 2014)
Answer:
The ButtonGroup control manages the selected/unselected state for a set of buttons. For the group, the ButtonGroup instance guarantees that only one button can be selected at a time. Generally, we use Radio Button control with a button group.

Question 2.
Which property of ListBox is used to display the values in the list? (Delhi 2014)
Answer:
The model property of the ListBox is used to display values in the list.

Question 3.
Write Java statement to make a jTextFieldl uneditable during execution. (Delhi 2014)
Answer:

jTextFieldl.setEditable(false);

will make jTextFieldl uneditable during execution.

Question 4.
Write Java statement to make a jTextFieldl disabled. (All India 2014)
Answer:

jTextField1.setEnabled(false);

Question 5.
Which property of palette ListBox is used to enter the list of items while working in NetBeans? (HOTS; Delhi 2013)
Answer:
The model property of palette ListBox is used to enter the list of items while working in NetBeans.

Question 6.
Write a Java statement to make the jTextFieldl non-editable. (All India 2013)
Answer:

jTextFieldl.setEdi table(false);

Question 7.
What will be displayed in jTextAreal after executing the following statement; (Delhi 2012)

jTextAreal.setText(“INDIAXnINCREDIBLE UINDIA”);

Answer:

INDIA
INCREDIBLE INDIA

Question 8.
What will be the content of the jTextAreal after executing the following code? (Delhi 2012C)

int Num = 4;
jTextAreal.setText(Integer.toString(++Num));

Answer:
When the given code is executed, the following output will be produced 5.

Question 9.
What message will be displayed after the execution of the following code? (HOTS; Delhi 2012)

int Age = 24.Relaxation = 6; 
int Modi Age = Age-Relaxation; 
if(ModiAge < 18)
J0ptionPane.showMessageDia1og(null, “NOT eligible”); 
else
JOptionPane.showMessageDialog(null. “Eligible”);

Answer:
The output of the following code will be produced in message box: Eligible

Question 10.
What message will be displayed after the execution of the following code? (All India 2012)

int Age = 64, Relaxation = 4; 
int Modi Age = Age-Relaxation; 
if(ModiAge < 18)
JOptionPane.showMessageDialog (null, “NOT eligib!e”); 
else
JOptionPane.showMessageDialog (null, "Eligible”);

Answer:
When given code is executed, the following output will be produced in message box: Eligible

Question 11.
Rewrite the following program code using if statement: (HOTS; Delhi 2012)

int C=jComboBoxl.getSelectedIndex(); 
switch (C)
{
case 0:
Final Amt = Bill Amt; 
break; 
case 1:
Final Amt = 0.9*Bill Amt; 
break; case 2:
FinalAmt = 0.8*Bill Amt; 
break; 
default:
FinalAmt = Bill Amt;
}

Answer:
The rewritten code with the use of if, will be as follows:

int C =jComboBoxl.getSelectedIndex(); 
if (C == 0)
Final Amt = Bill Amt; 
else if (C == 1)
Final Amt = 0.9*Bi11 Amt; 
else if (C == 2)
Final Amt = 0.8*Bill Amt; 
else
Final Amt = Bill Amt;

Question 12.
Rewrite the following program code using if statement: (All India 2012)

int C =jComboBoxl.getSelectedIndex( ); 
switch (C)
{
case 0:
Amount = Bill; 
break; 
case 1:
Amount = 0.9*Bill; 
break; 
case 2:
Amount = 0.8*Bill; 
break; 
default:
Amount = Bill;

Answer:
The rewritten code with the use of if, will be as follows:

int C =jComboBoxl.getSelectedIndex(); 
if (C == 0)
Amount = Bill; 
else if (C == 1)
Amount = 0.9*Bi11; 
else if (C == 2)
Amount = 0.8*Bill; 
else
Amount = Bill;

Question 13.
What will be displayed in jTextAreal after executing the following statement? (Delhi2011)

jTextAreal.setText(“Li ve\nln PeaceUand harmony”);

Answer:
The output of the given statement:

Live 
In Peace and harmony

Question 14.
Given a String object namely “value”, having value as “324” stored in it. What will be result of the following? (Delhi2011)

JOptionPane.showMessageDialog(null,
“ ” + (value.TengthO+Integer. 
parselnt(va1 ue)));

Answer:
The output of the given statement in message box:
327

Question 15.
What will be displayed in jTextAreal after executing the following statement? (All India2011)

jTextAreal.setText
(“cbse\nFinal_Exam\tIP”);

Answer:
The output of the given statement:

cbse 
Final_Exam IP

Question 16.
Given a String object namely “subject”, having value as “123” stored in it. What will be result of the following? (All India 2011)

JOptionPane.showMessageDialog(null” +(subject.length(HInteger. parselnt(subject)));

Answer:
The output of the given statement in message box:
126

Question 17.
How the use of layout manager is important?
Answer:
Layout Managers
The layout managers are used to set the control of the visual components used with a GUI form to determine the size and position of the component within the container. There are various layout managers used in the swing control. These are as follows:

  1. BorderLayout The BorderLayout manager arranges the components of a container in North, South, East, West and Center position of the container.
  2. FlowLayout The FlowLayout manager arranges the components of a container line wise from left to right in row. If there are more control that cannot be fitted within a line, then those are shifted to successive lines.
  3. Grid! ayout The GridLayout manager places the components of a container in a grid of equally sized cells. These grids are added from left to right direction and top to bottom direction.
  4. CardLayout The CardLayout manager helps in managing many controls that are occupying the same display area. These components are of same size occupying the same display area, so only the top card is visible at any time. At the design time, with the help of Inspector windows, we can define which component will be displayed at the top.
  5. GridBagLayout The GridBagLayout manager can provide precise control over all aspects of the layout. Whenever we are resizing the container, it maintains a consistent appearance across platforms.
  6. SpringLayout The SpringLayout manager helps in defining the directional relation between the edges of the components.
  7. BoxLayout The BoxLayout manager helps in arranging multiple components in either vertical or horizontal direction. The components are arranged either in left to right or top to bottom. i.e. in the way they are added to the container.

Question 18.
Explain container component.
Answer:
Components
A swing component is a graphical tool that can be customised according to the requirement of the user and inserted into the application, whenever needed. e.g. JButton, JTextField, JLabel, etc.

Container
A container is a type of component which can hold other components. e.g. JFrame, JApplet, JDialog, etc.
The components contained in a container are called child components. A container and its child components can be moved, hidden, shown in single operation. If you move a container then its child components will also move along with it.

A container can be divided into two categories:
(i) Top-Level Container A top-level container is that container which can be displayed on the desktop directly.
(ii) Non-Top-Level Container A non-top-level container is that container, which can be displayed within the context of another top level component. It can be used for general purpose or specific purpose.

Question 19.
What is an event? What is event handler?
Answer:
Events Haiidfing
The events are the occurrence of some activity either initiated by the user or internally by the program or the computer itself. For handling the events, there are three essential things namely the event source, the event handler and the event object.

  1. Event source The event source is the GUI component e.g. when a button is clicked it generates an event so, button is an event source. When at runtime the cursor is placed within the textfield then focusgained event is generated, in this case, text field would be an event source.
  2. Event handler The event handler or event listener, analysis the received event and after computing some value according to defined procedure, the same is displayed for the user’s reference.
  3. Event object Whenever during the execution of the program the event is generated, the event object is created and is passed to the event listener.

Defining an Event Handler For defining the event handler, we can follow these steps:

  1. First we have to select the component.
  2. Then, we need to click on the event tab in the properties window or we can right click on the component and select the desired event from the submenu on the contextual menu.
  3. Thereafter, we need to type the source code in the source code edìtor for handling the event related to that particular component.

Question 20.
Why are we using the label?
Answer:
Label
The label is a swing control, which is used to display an uneditable text or image. A label is created through JEabel component. The text to be displayed in the label is provided in the text property of the label or through programming code to be accessed at run time.

Question 21.
Which command is needed to make a button work as an Exit button?
Answer:
To make a button work as Exit button, we need to write in action performed( ) event handler of the button and then we write the following command:

System.exit(O);

Question 22.
What will be the contents of jTextAreal after executing the following statement?

jTextAreal.setText(“Object\nOriented \tProgramming”);

Answer:
When the given code is executed, the following output will be produced:
Object-Oriented Programming

Question 23.
Explain the purpose of the following statement?

jTextFieldl.setText(“Informatics”, substring(3));

Answer:
It will store the first three characters of the given string “Informatics” in the given text field jTextField 1. It means the “Inf” will be displayed in the text field.

Question 24.
Explain confirm dialog box? How will you create a confirm dialog box?
Answer:
Dialog Box Type
We can create four types of predefined dialog boxes. These are as follows:

  1. Input dialog This type of dialog box is used to enter the data. We can use JTextField, JComboBox or JList. There are two buttons OK and Cancel. To create an input dialog box, the showInputDialog( ) method is used.
  2. Confirm dialog This type of dialog box is used to ask from the user about the confirmation of any information. It includes buttons Yes / No, OK and Cancel, etc. To create a confirm dialog box, the showConfirmDialog( ) method is used.
  3. Message dialog The message dialog box is used to simply display some information to the user. It includes only a single OK button. To create a message dialog box, the showMessageDialog( ) method is used.
  4. Option dialog The option dialog is a flexible type. It can be used to create a dialog box according to the user’s need.
    To create an option dialog box, the showOptionDia!og( ) method is used.

2 Marks Questions

Question 25.
Name methods used to perform the following in NetBeans:
(i) To set component visible at run time.
(ii) To return the index value of the selected item from the list. (Delhi 2014)
Answer:

(i) setVisible(true);
(ii) getSelectedlndexl);

Question 26.
What will be display in jTextAreal after the execution of the following code? (Delhi2014)

int Z=4; 
do 
{
jTextAreal.setText(Integer. 
toString(++Z));
Z=Z+1;
}while (Z<=8);

Answer:
9 will be displayed in j Text Areal after the execution of the given code.

Question 27.
Give the output of the following lava code: (Delhi 2014)

String name="Sid Nayar”; 
int T=name.length!),N;
N=150—T;
JTextField2.setText
(Integer.toString(T)); 
jTextField3.setText
(Integer .toStri ng(N));

Answer:

jTextField2 will contain 9 and jTextField3 will contain 141.

Question 28.
What will be the content of jTextAreal and jTextFieldl after the execution of the following statement? (Delhi 2014)

(i) jTextAreal. setText ("Just\tAnother\nDay”);
(ii) String Subject= “Informatics Practices”; 
jTextFieldl.setText
((Subject.length()+10)+“ ”);

Answer:
(i) Just Another
(ii) 31 Day

Question 29.
Rewrite the following program code using an if statement: (Delhi 2013)

String Remarks;
int Code = Integer.parselnt
(jTextFieldl.getText()); 
switch(Code)
{
case 0: Remarks = "100% Tax
Exemption”; 
break;
case 1: Remarks = "50% Tax Exemption”;
break;
case 2: Remarks = “30% Tax
Exemption”; 
break;
default:
Remarks = "!Invalid Entry”;
}

Answer:

String Remarks;
int Code = Integer.parselnt 
(jTextFieldl,getText()); 
if (Code == 0)
{
Remarks = “100% Tax Exemption”;
}
else if (Code == 1)
{
Remarks = “50% Tax Exemption”;
}
else if (code == 2)
{
Remarks = “30% Tax Exemption";
}
else
{
Remarks = “!Invalid Entry”;
}

Question 30.
Write a Java code that takes value for side of a square in jTextFieldl and calculate area of it to be displayed in jTextField2. (Delhi 2012)
Answer:

int s=Integer.parselnt
(jTextFieldl.getText()); 
int a=s*s;
jTextField2.setText(“ ”+a);

Question 31.
Write a Java code that takes value for a number(n) in jTextFieldl and cube (n*n*n) of it to be displayed in jTextField2. (All India 2012)
Answer:

int n=Integer.parselnt
(jTextFieldl,getText()); 
int c= n*n*n;
jTextField2.setText(“ ”+c);

Question 32.
Write a Java code that takes the cost of a pencil
from jTextFieldl and number of pencils from jTextField2 and calculate total amount as cost * quantity to be displayed in jTextField3 and also find 20% tax amount to be displayed in jTextField4. (All India 2011)
Answer:

double a, b, c, d; 
a=Double.parseDouble
(jTextFieldl.getText()); 
b=Double.parseDoubl e
(jTextField2.getText()); 
c = a*b;
d = (c*20)/100; 
jTextField3.setText(“ ”+c); 
jTextField4.setText(“ ”+d);

Question 33.
Simran created an application with three radio buttons. Now, Simran has found that more than one radio button can be selected. How can Simran correct this error? (Delhi 2011c)
Answer:
First we have to create an object of panel and all radio button will be added in pannel as follows:

JPanel Pl=new JPanel (); 
Pl.add(jRadioButtonl);
PI.add(jRadioButton2);
PI.add(jRadioButton3);

Second we have to create an object of button group and all radiobutton is added into buttongroup object such as

ButtonGroup gl=new ButtonGroup(); 
gl.add(jRadioButtonl); 
gl.add(jRadioButton2); 
gl.add(jRadioButton3);

Question 34.
What will be displayed in jTextFieldl after executing the following code? (Delhi20ll)

int N = 20;
N = N + 1; 
if (N < 21)
jTextFieldl.setText(Integer. 
toString(N+10)); 
else
jTextFieldl.setText(Integer.
toString(N+l5));

Answer:
In jTextFieldl, after execution of the given code, following output will be displayed:
36

Question 35.
What is a combo box? What is the default state of a combo box? How can we set a combo box to editable or uneditable?
Answer:
The combo box is a combination of a list box and a text field. Infact, it will display a text field alongwith a drop-down list of values from which the user and selection a value at runtime. If the combo box is set to editable, then the user can either enter a value in the text field or select an option from the dropdown list.

By default the editable property of a combo box is uneditable. We can set the editable property of a combo box to true or false, to make it editable or uneditable, respectively by using setEditable (boolean b) method.

Question 36.
Define password field. Which property allows you to change the default character of password field?
Answer:
The password field is used to accept the password for an application during the execution of a program. The password field is similar to text field but the text displayed in a password field in form of echo character (echoChar).

The default character is *. It means whatever characters the user enters in this field during the execution of the program, an echo character (usually *) will be displayed for the same. To change the character to be displayed in the password field, we can use the echoChar property of the password field. Using this property, we can set a character in the echoChar field. Suppose, we want to change the default character to $, then we have to set $ character in the echoChar property.

Question 37.
Explain text area control. Which property used to set the color of the text to be displayed in the text area?
Answer:
The text area is a control which enables the user to enter multiline text. This control provides an editable area for blocks or multiple lines for the text. It means the user enter multiline text in this field. To set the text color of the text in the text area, we can set the desired color in the foreground property of the text area.

Question 38.
Which method is used to set the text area as editable or uneditable?
Answer:
To determine whether the text area is editable or not, we have to use the void setEditable(boolean b) method. This method is used to set whether the user can edit the text being displayed in text area or not i.e. to set the editable property to true or false. General syntax of this property is as follows:

<textarea_name>.setEditable(true): 
or
<textarea_name>.setEditable(false);

Question 39.
What is a checkbox? Which property is used to set a keyboard shortcut for the checkbox?
Answer:
The check box control is used to specify whether a particular condition is true or false. The user can select multiple options from a given list of options.
To set a keyboard shortcut, we use to Mnemonic property of the checkbox. Here, we have to specify the keyboard shortcut to be used to access the checkbox.

Question 40.
Name two containers for each level given below:
(i) Component level
(ii) Middle level
(iii) Top level
Answer:
(i) Component level container

  • jFrame
  • j Dialog

(ii) Middle-level container

  • jPanel
  • jTabbedPane

(iii) Top level container

  • jFrame
  • j Dialog

Question 41.
Briefly explain the two types of swing components?
Answer:
Types of Swing Controls
There are various types of swing controls in Java. These are defined hereunder:

  1. Basic Controls These controls are primarily used to get input from the user or to show some information. These are the simple controls, è.g. JButton, JList, JCheckBox, JRadioButton, JComboBox, etc.
  2. interactive Display The interactive display type controls display the formatted information which can be formatted by the user. The controls include JTextPane, J ColorChooser, JTable, JTextArea, etc.

Question 42.
What is a combo box? What are the advantages of combo box over list box?
Answer:
A combo box is a mixture of a text box and list box. It is a graphical control that displays a list of values in drop-down list form and a text field, where the user can enter a new value or can modify an existing value. The advantages of a combo box over list box can be understood with the following points:

  • A combo box takes less space on the screen, compared to a list box.
  • A combo box offers editing features through a text field but list box not.
  • In a combo box, only single item needs to be selected but in list box multiple items can be selected.

Question 43.
How a list is different from a combo box?
Answer:
A list is different from the combo box. Common basis of difference of a list and combo box can be stated in following points:

  1. A list does not have a text field, whereas a combo box is a combination of a text field and a list.
  2. The list displays all items inside it together i.e. it does not drop-down, so it takes more space on the screen, whereas a combo box has a drop-down control. Initially the combo box takes less space on the screen, when the user clicks on the arrow, which at the right of the combo box it drops-down.
  3. In a list, one or more items can be selected, whereas from a combo box only one item can be selected.
  4. In a list, the user has to select the desired item directly from the list, whereas in a combo box the user can either select the items from the list or enter it directly in the text box.

Question 44.
Differentiate between a text field and text area.
Answer:
A text field is used to accept an input from the user at runtime. It is an object of the class JTextField, which is displayed as a field and where the user can enter a single line of text. It can also be used to display the text as a result of an operation. It can also be made uneditable. In such situation, the text field will display uneditable text.

Whereas the text area is a control which enables the user to enter multiline text. This control provides an editable area for blocks or multiple lines for the text. Like the text box, it can also be made uneditable, to display multiple lines of output only.

Question 45.
Why an Exit button is used? How can you create an Exit button?
Answer:
An Exit button is used to close an application. To create an Exit button, we have to follow these steps:

  • First of all we have to create a button in the application of JButton component type.
  • Using the text property, we have to set the text as Exit.
  • Thereafter we have to add an action event listener to the button. For this we have to double click the button in the design view (alternatively, we can click on the event handler name actionPerformed in the event tab of property window).
  • Then we need to type the following code to action Performed!) method:
System.exit(O);

Question 46.
What is the importance of button group? How can we create a button group?
Answer:
A button group can be created to make a group of buttons that are mutually exclusive. It means when we select a particular button other buttons will be automatically cleared and in a group only one button could be selected. Usually, radio buttons show such type of behaviour. To create a button group, we follow these steps:

  • First we have to add a container ( like a panel) to hold the set of radio buttons.
  • Thereafter we give the panel titled border (though this step is optional).
  • Click at the button group control on palette and drag the same to the design space.
  • Thereafter for each selectable option, we have to add a JRadioButton to the container panel.

Question 47.
How is a getText() method different from a getPassword() method?
Answer:
The getText() method returns the text displayed by the text field. For instance, if a text field jTextl contains the word “Computer”. Then, if we apply the following code segment:

String result = jTextl.getText!); 
System.out.println(result);

The result will show “Computer” as output. Whereas the getPassword( ) method is used with a password field. It returns the text displayed by a password field. For instance, if a password field jPassI contains the word “PASS”.
Then, if we apply the following code segment:

String result = String.valueof
(jPassl.getPassword!)); 
System.out.println(result);

The result will show “PASS” as output.

Question 48.
What is the use of following methods?
(i) isEditable()
(ii) setEditable()
(iii) getEchoChar()
Answer:
(i) isEditable( ) This method determines whether a text field is editable or not. It is a boolean method which returns either true or false, to state if the specified text field or text area is editable or not.
(ii) setEditable() This method is used to make a text field editable or not. This is a boolean method, which is used to set the state or text field or text area to true or false, to state whether we want to make the text field or text area editable or uneditable.
(iii) getEchoChar( ) This method returns the echo character, i.e. the character which is displayed in the password field. By default it is *. But we can change it to any other character by using the setEchoChar(Char) method.

Question 49.
Why LineWrap and WrapStyleWord properties of a text area are used?
Answer:
LineWrap The LineWrap property determines whether a line of text in a text area should wrap, if it is too long for the allocated width of the component. We can set true or false value for this property. The default value is false.

WrapStyleWord The WrapStyleWord property of text area determines, where the wrapping occurs. We can set it to true or false. If it is set to true the wrap will be attempted only at the word boundaries. This property will work only when the line wrap property is set to true otherwise it is ignored. The default setting for the property is false.

Question 50.
Explain the significance of a checkbox. What are the common properties of a checkbox?
Answer:
The checkbox control is used to specify whether a particular condition is true or false. The checkbox can be used in the applications, where the user has to give True/False or Yes/No values in response of given statements. The user can select multiple options from a given list of options. For properties,

Properties

  • Foreground This property is used to set the font color or the foreground color of the check box.
  • Font It is used to set the font for the checkbox.
  • Text This property is used to set the text to be displayed with the checkbox.
  • Mnemonic This property is used to set a keyboard shortcut or the access key for the checkbox.
  • Selected This option can be set to true or false. If it is set to true, it is displayed as checked otherwise unchecked. The default value is unchecked or false.
  • Button Group This option is used to set the group of buttons to which this control belongs.
  • Label We can set the checkbox label by replacing it with setText (String) method.

Question 51.
What is the use of radio button? Briefly specify some common properties of a radio button.
Answer:
The radio buttons are used to present a set of two or more choices out of them the user can select only one choice. The radio buttons are specified in form of a button group, so that only one option out of the given options could be selected. For properties,

Properties

  • Background It is used to set the background color of the radio button.
  • Foreground It is used to set the font color of the text displayed with the radio button.
  • Buttongroup It is used to specify the name of the group of button, to which the radio button belongs.
  • Font It is used to specify the font for the text to be displayed with the radio button.
  • Selected It can be set to true or false. If it is set to true, then the radio button will be displayed as selected. The default setting is false i.e. not selected.

Text It is used to specify the text to be displayed with the radio button. Enabled It is used to set whether the button is active or not.

Question 52.
Define label. How is it different from a text box?
Answer:
The label is a swing control which is used to display an uneditable text or image. The text to be displayed in the label is provided in the text property of the label. In Java language, the label is created through JLabel class type component. The actual text to display in the label is controlled by text property of the label and in any way it is not editable at runtime.

Whereas a text box or a text field provided in Java language is used to enter or display a single line of text. A text field can be made uneditable using the setEditable(boolean) property. In such case, the text field will display some message like a label only and the user cannot enter anything in this field

Question 53.
What is a layout manager? Briefly explain different layout managers used in Java.
Answer:
Layout Managers
The layout managers are used to set the control of the visual components used with a GUI
form to determine the size and position of the component within the container.
There are various layout managers used in the swing control. These are as follows:

  1. BorderLayout The BorderLayout manager arranges the components of a container in North, South, East, West and Center position of the container.
  2. FlowLayout The FlowLayout manager arranges the components of a container linewise from left to right in row. If there are more control that cannot be fitted with in a line, then those are shifted to successive lines.
  3. GridI..ayout The GridLayout manager places the components of a container in a grid of equally sized cells. These grids are added from left to right direction and top to bottom direction.
  4. CardLayout The CardLayout manager helps in managing many controls that are occupying the same display area. These components are of same size occupying the same display area, so only the top card is visible at any time. At the design time, with the help of Inspector windows, we can define which component will be displayed at the top.
  5. GridbagLayout The GridBagLayout manager can provide a precise control over all aspects of the layout. Whenever we are resizing the container, it maintains a consistent appearance across platforms.
  6. SpringLayout The SpringLayout manager helps in defining the directional relation between the edges of the components.
  7. BoxLayout The BoxLayout manager helps in arranging multiple components in either vertical or horizontal direction. The components are arranged either in left to right or top to bottom. i.e. in the way they are added to the container.

Question 54.
Briefly explain some common methods of push button.
Answer:
Methods
(i) void setText(String) This method sets the specified text on the button.

e.g. (button_name>.setTeXt(”PreSS the button’):

(ii) String getText() This method returns the text displayed on the button.

e.g. String result = <button_name>.getîeXtO;

Question 55.
What will be the output of jTextFieldl after executing the following code?

int Num = 6;
Num = Num+1; 
if(Num < 5)
jTextFieldl.setText(Integer. 
toString(Num)); else
jTextFieldl.setText 
(Integer.toString(Num+5));

Answer:
The output of the given code segment after execution will be as follows:
12

Question 56.
What will be output of jTextField2 after executing the following code?

int x = 5; 
x = x +10; 
if(x = =5)
jTextField2.setText 
(Integer.toString(x)); 
else
jTextField2.setText 
(Integer.toString(x-6));

Answer:
The output of the given code segment after execution will be as follows:

Question 57.
The salary of an employee is stored in a string variable strsalary. Now, it is required to store the salary value in double type variable DoubSalary. Write a Java statement to do the same.
Answer:
The Java statement to store the content of strSalary (which is in String form) in Double type variable DoubSalary variable will be as follows:

double DoubSalary = Double.parseDouble(strSalary);

Question 58.
Write the name of component classes for the following:
(i) Text field
(ii) Label
(iii) Text area
(iv) Radio button.
Answer:
The component classes for text field, label, text area and radio button are as follows:

(i) Text field JTextField
(ii) Label JLabel
(iii) Text area JTextArea
(iv) Radio button JRadioButton

Question 59.
How many type of dialog boxes we can create using Java?
Answer:
Dialog Box Type
We can create four types of predefined dialog boxes. These are as follows:

  1. Input dialog This type of dialog box is used to enter the data. We can use JTextField, JComboBox or JList. There are two buttons OK and Cancel. To create an input dialog box, the showlnputDialog() method is used.
  2. Confirm dialog This type of dialog box is used to ask from the user about the confirmation of any information. It includes buttons Yes I No, OK and Cancel, etc. To create a confirm dialog box, the show ConfirmDialog() method is used.
  3. Message dialog The message dialog box is used to simply display some information to the user. It includes only a single OK button. To create a message dialog box, the showMessageDialog() method is used.
  4. Option dialog The option dialog is a flexible type. It can be used to create a dialog box according to the user’s need. To create an option dialog box, the showOptionDialog() method is used.

Question 60.
Which methods are used to count number of columns and number of rows in a given table.
Answer:
For counting the number of columns in a given table the getColumnCount() method is used. The format of getColumnCount() method is as follows:

int getColumnCount();

For counting the number of rows in a given table getRowCount() method is used. The format of this method is as follows:

int getRowCount()

Question 61.
Briefly explain the procedure to add a new row in a given table.
Answer:
Adding a New Row into the Table
To add a new row in the table, we have to follow these steps:
(i) Firstly, keep in your mind, the structure of the table should be in exact order i.e. the name of the columns and the data types being stored should be in order.
(ii) Then, we have to create an object array out of in order data for the new row to be added in the table as per following

syntax: Object newrow[] — {values...};

These values can be specified in the form of values or obtained values from the text boxes.
(iii) Thereafter, obtain the model for the table as per following syntax

DefaultlableModel <identifier) — (DefaultTableModel)table_narne.getModel();

If the above statement shows error then import the required package as follows: import javax.swing.table.*:
(iv) Thereafter, we have to add the object array created in step (ii) into the model created in step (iii) by using the addRow() method as per following syntax:

<Default_table_model_object>.addRow(<object_array....containing row_data>);

Question 62.
Write a Java code that takes the price of a pencil from jTextFieldl and quantity of pencils from jTextField2 and calculate total amount as price * quantity to be displayed in jTextField3 and also find 10% tax amount to be displayed in TextField4. (CBSE Textbook)
Answer:

double a, b, c, d;
a= Double.parseDouble
(jTextFieldl.getText()); 
b=Double.parseDouble
(JTextField2.getText()); 
c = a * b; 
d = c * 10/100; 
jTextField3.setText(" ”+c); 
jTextField4.setText(“ ”+d);

Question 63.
Write a program in Java to calculate the result of power raised to a given number.
Answer:

// Calculate the value of NumberRaise using the pow() function double Number,Raise,Result;
Number=Double.parseDoubletjTextFieldl.getText());
Raise=Double.parseDouble(jTextField2.getText());
Result=Math.pow(Number, Raise); 
jTextField3.setText(Double.toString(Result));

Question 64.
Write a function in Java that takes two numbers as input from text fields and displays their sum.
Answer:

double a = Double.parseDoubletjTextFieldl,getText()); 
double b = Double.parseDoubletjTextField2.getText()); 
double c = a + b;
jTextField3.setText(“ ” +c);

Question 65.
Write a code in Java that takes principal, rate and time as input from text fields and displays simple interest.
Answer:

double p = Double.parseDoubletjTextFieldl,getText()); 
double r = Double.parseDoubletjTextField2.getText()); 
double t = Double.parseDouble(jTextField3.getTextt)); 
double i = (p * r * t)/ 100; 
jTextField4.setText(“ ” +i);

Question 66.
Write a program in Java to find the perimeter and area of a rectangle, which will accept the length and breadth from the user and display the area and perimeter, when the user clicks at the Calculate button. Also, write code for Exit button to close the application.
Answer:
Double click at the calculate button (jButtonD and enter following code:

Private void jButtonlActionPerformedtjava.awt.event.ActionEvent evt)
{
double a = Double.parseDoubletjTextFieldl.getTextt));
double b = Double.parseDoubletjTextField2.getTextt));
double c = 2*(a + b);
double d = a*b;
jTextField3.setText(“ ”+c);
jTextField4.setText(“ ”+d);
}

Double click at the Calculate button (jButton2) and enter following code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(O);
}

Question 67.
Write a program in Java to find the circumference and area of a circle, which accepts the radius from the user and displays the area and circumference, when the user clicks at the Calculate button. Also, write code for Exit button, to close the application.
Answer:
First, we have to double click at the Calculate button (jButtonl) and enter the following code:

private void jButtonlActionPerformedtjava.awt.event.ActionEvent evt)
{
double r = Double.parseDouble(jTextFieldl.getTextt));
double c = 2 * (22/7) * r;
double a = (22/7) * r * r;
jTextField2.setText(" ”+c);
jTextField3.setText(“ ” +a);
}

Now, we have to double click at the Exit button (jButton2) and enter the following code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}

Question 68.
Create a program in Java that accepts distance in kilometre and converts it into metre, when the user clicks at Convert button. Also, write code for, create an Exit button to close the application.
Answer:
First, we need to double click at Convert button and type the following code:

private void jButtonlActionPerformed(java.awt.event.ActionEvent evt)
{ 
double a = Double.parseDouble(jTextFieldl.getTextO); 
double b = a*1000; 
jTextField2.setText(“ ” +b);
}

After that double click at the Exit button (jButton 2) and type the following code

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(O);
}

Then, we can save and run the program.

Question 69.
Write a program in Java that accepts two numbers from the user. Also, create two buttons named Sum and Product. When the user clicks at Sum button, the sum of two numbers should be displayed in the Result text box. When the user clicks at Product button, the Product of two given number from text boxes be displayed. Also write code for Exit button to close the application.
Answer:
For creating a program according to the given problem, we have to follow these steps:
(i) First we have to design the interface by using these steps:

  • First add a new JFrame form in the application.
  • Now, add the following components on the form:
    • Two editable text fields to accept two numbers.
    • One non-editable text field to display the Result.
    • Four buttons Sum ( for calculating and displaying the sum of two given numbers), Product ( for calculating and displaying the product of two given numbers) Clear (to clear the text fields) and Exit (for exiting from the application).
    • Three labels one against each of the text field to appropriately direct the user.

Now, the interface will look like as follows:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 1
(ii) Now, we have to double click at the Sum button (jButton 1) and type the following code:

private void jButtonlActionPerformed(java.awt.event.ActionEvent evt)
{
double a = Double.parseDoubletjTextFieldl.getTextO); 
double b = Double.parseDouble(jTextField2.getTextC)); 
double c = a + b; 
jTextField3.setText(" ” +c);
}

(iii) Now, we need to double click at the Product button (jButton2) and type the following code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
double a = Double.parseDouble(jTextFieldl.getText()); 
double b = Double.parseDoubleCjTextField2.getText()); 
double c = a * b; 
jTextField3.setText(“ ”+c);
}

(iv) Then, we have to double click at the Clear button (jButton3) and type the following code:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextFieldl.setTextC" ”); 
jTextField2.setTextC" ”); 
jTextField3.setTextC" ”):
}

(v) Lastly, we have to double click at the Exit button (jButton4) and type the following code:

private void jButton4ActionPerformedCjava.awt.event.ActionEvent evt)
{
System.exit(O);
}

Question 70.
Write a program that accepts three numbers from the user and displays the greatest number out of three numbers in a label.
Answer:

double a = Double.parseDoubleCjTextFieldl.getTextC)); 
double b = Double.parseDoubleCjTextField2.getText()); 
double c = Double.parseDoubleCjTextField3.getText()); 
double g;
if(a>b && a>c) 
g=a;
else if(b>a && b>c) 
g=b; 
else 
g=c;
jTextField4.setTextC" ”+g);

Question 71.
Write a program in Java that accepts marks of a student in three subjects in three different text fields and displays the sum in fourth text field. If the total is greater than 225, A should be displayed in the grade field otherwise B should be displayed.
Answer:

double a = Double.parseDoubleCjTextFieldl.getTextC));
double b = Double.parseDoubleCjTextField2.getText()); 
double c = Double.parseDoubleCjTextField3.getText()); 
double d = a + b + c;
jTextField4.setTextC" ”+d); 
if(d>=225)
jTextField5.setText(“A”);
else
jTextField5.setText(“B”);

4 Marks Questions

Question 72.
Janav Raj is a programmer at Path Educo Enterprises. He created the following GUI in NetBeans. Help him to write code for the following:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 2
(i) To display series of odd or even numbers (depending on Starting Number-jTextFieldl is even or odd) in the jTextArea on the click of command button [Display The Series], e.g. If the Start Number is 5 and Last Number is 11 Text Area Content will be 5 7 9 11 If the Start Number is 2 and Last Number is 10 Text Area Content will be 2 4 6 8 10
(ii) To clear both the text fields and text area, on clicking [Reset] button.
(iii) To terminate the application on the click of [Stop] button. (All India 2012)
Answer:

(i) int start=Integer.parseInt(jTextFieldl.getText());
int last=lnteger.parselnt(jTextField2.getText()); 
for(int i=start;i<=last;i=i+2)
{
jTextAreal.appendC" ”+i);
}

(ii) jTextFieldl.setTextC" ”); 
jTextField2.setTextC" ”): 
jTextAreal.setTextC" ”);

(iii) System.exit(O);

Question 73.
Mr. Ram Kishore, the owner of Kiddi Land Enterprises has asked his programmer Saumya to develop the following GUI in NetBeans.
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 3
Mr. Ram accepts payment through three types of credit cards. The offer is given according to the following schemes:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 4
If the Bill Amount is more than? 25000, then the customer gets an Additional Offer of 5%.
Write the Java code for the following:
(i) To assign Additional Offer as 0 (jTextFieldA) and Net Amount as 0 (jTextField5). Also set them as uneditable.
(ii) [When “Calculate Offer” (jButtonl) is clicked]
(a) To calculate discount as per the given criteria and display the same in jTextField3.
(b) To assign Additional Offer (jTextField4) as 5% of amount (jTextField2) as per the above condition.
(c) To enable “Calculate Net Amount” (jButton2) button.
(iii) [When “Calculate Net Amount” (jButton2) button is clicked]
(a) To calculate net amount as [Total Cost (jTextField2) – Offer (jTextField3)] -Additional Offer (jTextField4).
(b) To display the Net Amount in jTextField5. (Delhi 2011; All India 2011)
Answer:
(i) Just write the following statements:

jTextField4.setText("0”); 
jTextField5.setText(“0”); 
jTextField4.setEditable(false); 
jTextField5.setEditablet false);

(ii) Thereafter, we have to double click at the Calculate Discount button (jButtont) and enter the following code:

double amt = Double.parseDouble(jTextField2.getText()); 
double dis=0, disl, dis2=0;
if(jRadioButtonl.isSelected()== true) dis=20; 
else if(jRadioButton2.isSelected( )==true) dis=15; 
else if(jRadioButton3.isSelected()==true) dis=10; 
disl = amt * dis /100; 
if(amt > 25000) dis2 = amt * 5 / 100; 
jTextField3.setText(" ” +disl); 
jTextField4.setText(“ ” +dis2);

(iii) After that double click at Calculate Net Amount button (jButton2) and enter the following code:

double amt = Double.parseDouble(jTextField2.getText()); 
double dis = Double.parseDouble(jTextField3.getTextt));
double disl = Double.parseDouble(jTextField4.getText()); 
double netamt = amt - dis - disl; 
jTextField5.setText(" ” +netamt);

Question 74.
Glamour Garments had developed a GUI application for their company as shown below:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 5
The company accepts the payments in three modes as Cheque, Cash and Credit Cards. The discount given as per mode of payment is as follows:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 6
If the Bill Amount is more than 15000, then the customer gets an additional discount of 10% on Bill Amount.
(i) Write the code to make the text fields for Discount (named txtDisc) and Net Amount (named txtNetAmt) uneditable.
(ii) Write code for the following:
(a) When “Calculate Discount” button is clicked the discount should be calculated as per the given criteria and it should be displayed in the Discount text field. “Calculate Net Amount” button (Named CalcNetAmt) should be enabled.
(b) When “Calculate Net Amount” button is clicked the Net Amount should be calculated and it should be displayed in the Net Amount text field.
Answer:
(i) First, we need to click at any blank area of the JForm and click at the source tab button and type
following codes to make the Discount text field and Net Amount text field uneditable

initComponents();
txtDisc.setEditable(false);
txtNetAmt.setEditable(false);

(ii) Then, we need to double click at the Calculate Discount button (jButtonl) and type the following code:

(a) double amt = Doubl e.parseDoubl e( jTextFi el d2.getText()); 
double d;
if(jComboBoxl.getSelectedIndex()==0) 
d = 8;
else if(jComboBoxl,getSelectedIndex()==1) 
d = 7;
else
d = 0;
double dis = amt * d /100; 
txtDisc.setText(“” +dis);
CalcNetAmt.setEnabled(true);
// It will enable the Calculate Net Amount Button

(b) Click at the Net Amount button and type the following codes:

double amt = Double.parseDouble(jTextField2.getText()); 
double dis = Double.parseDouble(txtDisc.getText()); 
double net = amt - dis;
textNetAmt.setText(" ” +net);

Question 75.
Richika is a programmer at Apha Builders. To calculate wages to be paid to labourers. She has developed the following GUI in NetBeans:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 7
Male and Female labourers are respectively paid at the rate of? 140 per day and? 160 per day. Skilled labours are paid extra at the rate of? 50 per day.
(i) What should be done so that only one of the radio buttons (Male and Female) can be selected at a time?
(ii) Write code to do the following:
(a) Calculate and display the Total Wage in the corresponding label when the “Calculate Wage” button is pressed.
(b) Clear the Name and Number of Days worked text fields.
(c) Close the application when the “STOP” button is clicked.
(You can assume suitable names for various controls on the form)
Answer:
(i) Both the radio buttons should be put in a button group.
(ii)

(a) int WageRate, NoofDays, TotalPay;
if(radMale.isSelected())
wage rate = 140; 
else WageRate = 160; 
ifCchkskil1ed.isSelected())
wage rate += 50;
NoofDays = Integer.parseInt(JTextField2. getTextO)
Total Pays = NoofDays * Wage Rate; 
jTextField3.setText(Totalpay+‘‘ ”);

(b) TextName.setText(“ ”);
TxtDays.setText!“ ”);

(c) System.exit(0);

Question 76.
Mr. Amitabh Bachhan needs an Interest Calculator. Fie has instructed his software developer to develop a program as per following interface:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 8
(i) Write a code to deactivate the text fields for Amount and Interest i.e. jTextField3 and jTextField4, respectively.
(ii) Write a code for Calculate button (jButtonl) to calculate the Amount and Interest.
(iii) Write a code to clear all the text boxes and set the choice in Time radio buttons to 1 year.
(iv) Write code for Exit button to close the application.
Answer:
(i) First, we need to click at any blank area of the JFrame and click at the source tab button and type
following codes to make the Amount text field and Interest text field uneditable

initComponents!);
jTextField3.setEditable!false);
jTextField4.setEditable!false);

(ii) Thereafter, click at the Calculate button and type the following code:

double t;
double p = Double.parseDouble(jTextFieldl.getText!)); 
double i = Double.parseDouble(jTextField2.getText!)); 
if(jRadioButtonl.isSelected!))
t = 1;
else if(jRadioButton2.isSelected!))
t = 2; 
else
t = 3;
double c = p*i*t/100; double d = p+c;
jTextField3.setText(" ” + d); 
jTextField4.setText(“ ” + c);

(iii) Then, we need to double click at the Clear button and enter following codes:

jTextFieldl.setText!" ”);
jTextField2.setText(“ ”); 
jTextField3.setText(“ ”); 
jTextField4.setText(“ ”);
jRadioButtonl.setSelected!true);

(iv) After that we have double click at the Exit button and enter the following code:

System.exit(0);

Question 77.
Write a code in Java that provides options to round off the given number up to 0 decimal place, 1 decimal place, 2 decimal place and 3 decimal place.
Answer:
Sample figure for the question is given below:
Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls 9
(i) Thereafter, for 1st Radio button, we have specify the following code:

private void jRadioButtonlActionPerformed(java.awt.event.ActionEvent evt)
{
double Number,RoundedNumber;
Number=Double.parseDouble(jTextFieldl.getText());
RoundedNumber=Math.round!Number); 
jTextField2.setText(Double.toString(RoundedNumber)); 
}

(ii) For 2nd Radio button, the required code will be as follows:

private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
double Number, RoundedNumber:
Number=Double.parseDouble(jTextFieldl.getText!));
RoundedNumber=Math.round!Number*10)/10.0;
jTextField2.setText!Double.toString!RoundedNumber));
}

(iii) For 3rd Radio button, the required code will be as follows:

private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
double Number, RoundedNumber;
Number=Double.parseDouble(jTextFieldl.getText!));
RoundedNumber=Math.round!Number*!00)/100.0; 
jTextField2.setText(Double.toString! RoundedNumber));
}

(iv) For 4th Radio button, the required code will be as follows:

private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
double Number,RoundedNumber:
Number=Double.parseDouble(jTextFiel dl.getText!));
RoundedNumber=Math.round!Number*!000)/1000.0;
jTextField2.setText(Double.toString!RoundedNumber));
}

(v) Thereafter, we can save and run the program.

We hope the Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls help you. If you have any query regarding Informatics Practices Class 12 Important Questions Chapter 4 Swing Controls, drop a comment below and we will get back to you at the earliest.