JAVA GUI PROGRAMMING USING SWING-I
JAVA GUI PROGRAMMING USING SWING-I
Type A: Very Sho
Type A: Very Short
rt Answ
Answer Questi
er Questions
ons
11 WWhhaat t iis s GGUUI I pprrooggrraammmmiinngg?? Ans.
Ans. GUI stands for Graphical User Interface. GUI stands for Graphical User Interface. A program's graphical user interface presents an easyA program's graphical user interface presents an easy -to-use visual display to-to-use visual display to the user. It is made up of
the user. It is made up of graphical components (e.g., bgraphical components (e.g., buttons, labels, windows)uttons, labels, windows).. 2
2.. WWhhaat t iis s JJaavva a JJFFCC?? Ans.
Ans. Swing API is part of a Swing API is part of a larger family of java products known aslarger family of java products known as Java Foundation ClassesJava Foundation Classes (JFC).(JFC). 3
3 HHoow w iis s SSwwiinng g rreellaatteed d tto o GGUUI pI prrooggrraammmmiinngg?? Ans.
Ans. The swing toolkit, shipped asThe swing toolkit, shipped as part of java SE platform, includes a rich set of graphical components part of java SE platform, includes a rich set of graphical components for building GUIs andfor building GUIs and adding interactivity to java applications.
adding interactivity to java applications. 4
4 WWhhaat t iis s ccoonnttaaiinneer r ccoommppoonneenntt?? Ans.
Ans. A container component is a special type of cA container component is a special type of c omponent that can hold other components. Some omponent that can hold other components. Some swing containers areswing containers are JPanel, JFrame etc.
JPanel, JFrame etc. 5
5 NNaamme e ssoomme e ttoop p lleevveel l ccoonnttaaiinneerrss.. Ans.
Ans. JFrame, JDialog, JAppletJFrame, JDialog, JApplet 6
6 NNaamme e ssoomme e ssppeecciiaal l ppuurrppoosse e ccoonnttaaiinneerrss.. Ans.
Ans. JInternalFrame, JLayeredPane, RootPaneJInternalFrame, JLayeredPane, RootPane 7
7 WWhhaat t iis s aan n eevveenntt? ? WWhhaat t iis s eevveennt t hhaannddlleerr?? A
Annss.. EEvveenntt is an occurrence of an activity.is an occurrence of an activity. Event handler
Event handler is a method that understands the event and processes it. is a method that understands the event and processes it. The event handler method takes the eventThe event handler method takes the event object as a parameter.
object as a parameter. 8
8 WWhhaat t iis s llaayyoouut t mmaannaaggeerr?? A
Annss.. LLaayyoouut t mmaannaaggeerr is a way to control arrangement, position and size of visual components on a is a way to control arrangement, position and size of visual components on a GUI form.GUI form. 9
9 NaName me at at leleasast tht threree Ee Evevent nt tytypepes ths that at cacan on occccur ur duduririnng an g an apapplplicicatatioion rn runun.. Ans.
Ans. 11.. WWiinnddoow Ew Evveennttss 2
2.. AAccttiioon En Evveennttss 3
3.. MMoouusse Ee Evveennttss 10
10 WhWhat at is is dedefafaulult lt layayouout mt mananagager er fofor a fr a frarame me anand fd for or a pa pananelel?? A
Annss.. ffrraamme –e –BoBordrderer LaLayoyoutut anandd papanenell ––FloFloww LayLayoutout 11
11 WhWhat iat is ths the dee defafaulult nat name me of of actactioion evn evenent hat handndleler or of a bf a bututtoton nn namamelely Tey TeststBiBin?n? An
Ans.s. TeTesstBtBininAcActitioonPnPererfforormemedd()()is the default name of action event handler of is the default name of action event handler of a button namely TestBin.a button namely TestBin. 12
12 WhWhy ay are re GUGUI cI comompoponenentnts ts thahat yot you au add dd toto yoyour ur apapplplicicatatioion an are re tetermermed ad as os objbjecectsts?? Ans.
Ans. GUI components which we add to our GUI components which we add to our application is termed as object because all basically are classes and when weapplication is termed as object because all basically are classes and when we add those component netbeans automatically create object of that r
add those component netbeans automatically create object of that r espective class.espective class. 13
13 NNaamme e ssoomeme pprrooppeerrttiiees s oof f JJFFrraamme e oobbjjeectct.. Ans.
Ans. title, cursor, iconImage, resizeable, defaultCloseOPeration.title, cursor, iconImage, resizeable, defaultCloseOPeration. 14
14 NNaamme se soome me pprrooppeerrttiiees os of Jf JPPaanneel ol obbjjeectct.. Ans.
Ans. background, border, foreground, toolTipText, preferredSize.background, border, foreground, toolTipText, preferredSize. 15
15 NaName me sosome me pproropperertitiees s oof f JJBuButtttoon n oobjbjeectct.. Ans.
Ans. actionCommand, background, border, font, foreground, icon,text.actionCommand, background, border, font, foreground, icon,text. 16
16 WhWhat at prpropopererty ty wowoululd yd you ou seset to t to asassisign gn acaccecess ss kekey ty to a bo a bututtoton?n? Ans.
Ans. mnemonicmnemonic 17
Ans. Returns the string set in actionCommand property of the button.
18 Which method can programmatically mimic the click action of a push button? Ans. doClick() method can programmatically mimic the click action of a push button.
Type B: Short Answer Questions
1. Discuss briefly about JFC and its constituent APIs.Ans. JFC expands to Java Foundation Classes. JFC is a suit of five libraries designed to assist programmers in creating enterprise applications.
1. Swing API
2. AWT (Abstract Window Toolkit) 3. Accessibility API
4. 2D API
5. Drag and Drop API
2 Differentiate between a container and a component.
Ans. container component
Container is a window-like component that can contain other components.
A component is an object, like a button or a scroll bar. Examples of containers are JPanel, JFrame, JApplet. Examples of components are JLabel, JTextField, JButton. 3 What are various categories of Swing controls? Give examples for each of them.
Ans. Following are the various categories of Swing controls:
1. Basic Control –JButton, JCheckBox, JComboBox, JList, JMenu, JRadioButton, JSlider, JSpinner, JTextField, JPasswordField.
2. Interactive Displays –JcolorChooser, JEditorPane, JTextPane, JFileChooser, JTable, JTextArea, JTree. 3. Uneditable Information Displays –Jlabel, JProgressBar, JSeparator, JToolTip.
4. Top-Level Container –Japplet, JDialog, JFrame.
5. General-Purpose Container –Jpanel, JScrollPane, JSplitPane, JTabbedPane, JToolBar. 6. Special-purpose Container –JinternalFrame, JLayeredPane, RootPane
4 Write steps to create a GUI application in java.
Ans 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.
5 Discuss briefly about different layout managers offered by Swing API.
Ans. Flow Layout: Default layout manager. It lays out the components from left to right
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 t he right choice.
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.
Card Layout: Different components at different times are laid out. Controlled by a combo box, determining which panel the Card layout displays.
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 le ft to right or top to bottom in the order they are added to the container.
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
1. A space hungry component is to be added at the centre of the frame. 2. Components should appear in a row.
3. Components should appear in rows and columns. Ans. 1. Border Layout
2. Flow Layout 3. Grid Layout
7 How does Java handle events?
Ans. Java handles the event by using 3 components - Event Source, Event Handler and Event Listener. When the user clicks on the event source which can be a button,
ActionEvent event is generated.
Then the ActionEvent object is created and linked to the listener which is ActionListener for processing.
The Listener object contains the actionPerformed() method which is event handler and this event handler processes the ActionEvent and our code is executed
8 Which event listeners would respond to following actions? 1. User moves the mouse
2. User presses a key on keyboard 3. User clicks a button
4. A component loses focus 5. Window is closed.
Ans. 1. Mouse Listener 2. Key Listener 3. Action Listener 4. Focus Listener 5. Window Listener 9 What are top-level containers? What is their significance?
Ans. 1. The top level containers are JFrame, JDialog, JApplet.
2. 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.
10 Name component classes for the following GUI components. 1. Text field 2. Text area 3. Label 4. Panel 5. Button Ans. 1. JTextField 2. JTextArea 3. JLabel 4. JPanel 5. JButton 11 Write code for both the buttons of following GUI application.
Ans. //Button1
jTextField2.setText("Non-resident Indian");
//Button2
jTextField2.setText("Central Board for Secondary Education");
12 Write code for event handler of each of the buttons in following application:
Button1 Initializes the value of label to 0 (zero) IntialValue Increment Decrement Button1 Button2 Button3 CalcLabel Button1 Button2 Full Form Label
Button3 Decrements the value of label by 1 (one) Ans. 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) {
i=i-1;
jLabel1.setText(Integer.toString(i)); }
TYPE C : Practical/Lab Questions
1 Design a GUI applicaton having an interface as shown below:
1. When user clicks on a button, Lable1 lists an image/picture of that tourist place. 2. The Text Area lists the package details for the selected tourist place.
3. Label2 shows some interesting information about the selected tourist place. Ans. // Shimla Button
jTextArea1.setText("");
jLabel1.setIcon(new ImageIcon("Mention You image file name with its path ")); jLabel2.setText("Shimla, is the capital city of the Indian state of Himachal Pradesh, located in northern India. ");
jTextArea1.append("Package"+'\n');
//Darjeeling Button
jTextArea1.setText("");
jLabel1.setIcon(new ImageIcon("Mention You image file name with its path")); jLabel2.setText("Darjeeling is a town in the Indian state of West Bengal."); jTextArea1.append("Package"+'\n');
//Srinagar Button
jTextArea1.setText("");
jLabel1.setIcon(new ImageIcon("Mention You image file name with its path")); jLabel2.setText("Srinagar is the most populous district in the state of Jammu and Kashmir,Indian Administered Kashmir and is home to the summer capital of
Label 1
Label 2
Jammu and Kashmir.");
jTextArea1.append("Package"+'\n');
// Kodaikanal Button
jTextArea1.setText("");
jLabel1.setIcon(new ImageIcon("Mention You image file name with its path ")); jLabel2.setText("Kodaikanal is a city in the hills of the taluk division of the Dindigul district in the state of Tamil Nadu, India. ");
jTextArea1.append("Package"+'\n');
// Pachmarhi Button
jTextArea1.setText("");
jLabel1.setIcon(new ImageIcon("Mention You image file name with its path ")); jLabel2.setText("Pachmarhi is a hill station in Madhya Pradesh state of central India, also known for the Pachmarhi Cantonment. It is widely known as Satpura ki Rani, situated at a height of 1100 m in a valley of the Satpura Range in
Hoshangabad district. ");
jTextArea1.append("Package"+'\n');
2 An institute offers MCA cources of duration 3 years. The interface given below is designed to capture the marks secured by student in the semester exams. Your help is sought to enhance the interface so that it is able to: 1. When user clicks the button Total, the total marks and the percentage of marks secured by the student
should be displayed in text txtTotal and txtPercent respectively. (Assume that the marks in each semester are out of 600)
2. When the user clicks on the button Report, the final repirt should be displayed in the label lblResult in the following format:
Total marks = ... and Percentage =… % //Total Button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int m1=Integer.parseInt(jTextField2.getText()); int m2=Integer.parseInt(jTextField3.getText()); int m3=Integer.parseInt(jTextField4.getText()); int m4=Integer.parseInt(jTextField5.getText()); int m5=Integer.parseInt(jTextField6.getText()); int m6=Integer.parseInt(jTextField7.getText()); int total=m1+m2+m3+m4+m5+m6; float per=total/36; jTextField8.setText(Integer.toString(total)); jTextField9.setText(Float.toString(per)); } //Report Button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int total=Integer.parseInt(jTextField8.getText()); float per=Float.parseFloat(jTextField9.getText());
jLabel8.setText("Total marks = "+total+" and Percentage ="+per+"%"); }
3 Design an application having interface as shown below:
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”); Ans. // SUBMIT BUTTON
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 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") } Text area