You are on page 1of 25
[Zi] introduction to swing + Swing is another programming in Java. «+ Swing creates highly interactive GUI applications, + Itis the most flexible and robust approach. [ZEA] swing Features ‘Swing has following two important features ~ approach of graphical 4. Piuggable Look and Feel: + Swing support several look and feels. Currently it includes support for Windows 98 and UNIX Motif. + Swing allows the user to switch look and feel at Tuntime without closing the current application. «+ Its possible to create your own look and feel for ‘swing components. 2. Lightweight Components : ‘+ Most of the Swing components are lightweight. That means using simple graphics primitive ‘components can be created. "| * With lightweight components, each component tenders itself using the drawing primitives of the Graphics object | Additional Features, 1. Swing contains wide variety of new components Such as tables, trees, sliders, progress bars and ‘so on, 2 ce ‘components can have tooltip placed over 3. It is possible to bind the keyboard events with the ‘components in Swing. 4. There'is a debugging support for rendering of created swing components. Limitations of AWT Following are some limitations of AWT - 1. AWT supports limited number of GUI components 2. The components defined by the AWT are heavy weight components 3. The behavior of AWT components varies when the container operating system changes. 4. The AWT components are developed by using the platform specific code, 5. The AWT component is converted by the native code of the operating system. [2:22 ] Ditforence between AWT and Swing “en Review Questions 1. What is Swing ? Give features of Swing 2. Differentiate between AWT and Swing 3. What are limitations AWT ?: [ZZ] swing Components + In order to display any JComponent on the cur, is necessary to add this component to the contai ‘first. + If you do not add these components to cont then it will not be displayed on the GUI. + The swing class component hierarchy is as’shi by following Fig. 2.2.1. + There are two important features of components - Firstly, all the component. cl begin with the letter J and secondly all these components are descendant of JComponent cl: Let us now learn how to place these components the GUI. [[ i667] betongs to java. tang, Object Fig. 2.2.4 fustnes ata Advanced jon Praraoning 2-3 [Zz] JFrame «+ In Java, Frame is a standard graphical window. «The frame can be displayed using the Frame class. + The frame drawn using this class has standard minimize, maximize and close buttons. «+ The syntax of frameé class is - 1) Frame) This creates the new instance’ of frame which is invisible initially. 1) Frame(String title) This creates the new instance of frame which has some title. + Following table enlists various methods of Frame A frame can be created by two ways - + By extending the Frame class +_By creating an instance of a Frame class. Ex221: Create a java frame by extending the Frame lass, Sol. : Java Program ‘import java.awt.*; _ ist FrameDemo extends Frame fae Static void main(String!} args) FrameDemo fr=new FrameDemo(); f-setSize(300,300); ae Note that initially the frame will not be visible. Hence ‘we need to set the visibility of the frame. Ex, 2.2.2 Frame class, Sol.: Create a java frame by using an instance of Java Program import java.awt."; class FrameDemo1 { 2) ublic static void main(Stringl] args) { Frame fr=new Frame(); fr.setSize(300,300); fr.setVisible(tru + } Output will be the same frame as above. [22Z]sapptet + The JApplet is a fundamental swing class. It extends the Applet class, ‘+ This is much more powerful than the Applet class. + It supports the pane. + Various panes are content pane, glass pane, and root pane, Up thrust for knowedgo Advanced Jaoa Programmi 2-4 © The add method can be used to add the content pane. © The add method of Container class can be used to add the components on the GUI. ‘* All the life'cycle methods used (such as init paint) in Applet class can be used with JApplet, Java Program[AppletDemo,java] import java.awt.*; import java.awt.event."; import javax.swing.*; /**/ Public class AppletDemo extends JApplet a ‘void paint(Graphics g) ‘ .drawString("WELCOME TO SWING PROGRAM',20,40); i How to run Swing applet program ? Open command prompt and type following command Techn —n Pubteatons An up tins fr knoetadaw Adoanced Java 25 Sings $223: Write a Swing program to display a smiley face Sol.: import java.awt.*; import java.awt.event.*; import javax.swing.*; /**/ public class smiley extends JApplet { public void paint(Graphics g) { g.drawOval(20,40,250,260); ‘g.drawOval(70,100,50,50) g.drawOval(180,100,50,50); g.drawAro(100,150,100,100,180,180); Program Explanation : In above program, (1) We have created a JApplet. This applet contains the paint method. The paint method is called to draw the output directly on the surface of the component. @) Using the object of Graphics class we can invoke the methods drawOval, drawAre rr Technical Pubcations”- An up thrust for knowledge ‘Adoanced Java Programming Icons and Labels - «The icons are encapsulated by Imagelcon class. The constructors are - Imagelcon(string fname) Imageleon{URL ut) ‘The fname denotes the name of the file which contains the icon. The url denotes the resource of image. ‘+ The JLabel is a component for placing the label component. The JLabel is a subclass of JComponent ‘lass. The syntax for the JLabel is - ‘TLabel(tcon io) Label(String 6); Shabel(Strng 5, Icon i, int alignment) + The alignment can be LEFT,RIGHT,CENTERLEADING and TRADING. ‘The icons and text methods associated with the label are- Icon geticon() ‘void setIcon(Icon ic) €1e represents the {con file String getText(); void setText(String ); €s represents the string + Following simple Java Program illustrates the use of JLabel component - Java Program|LabelProg,java] import java.awt.*; import javax.swing.*; Public class LabelProg extends JApplet { ‘public void init() { + Container contentPane=getContentPane(); Imagelcon i=new Imagelcon( "innocence ; ‘Label L=new JLabel(‘Innocence’,j,JLabel LEFT); contentPane.add(L1); Tectnkal Pubicatons - An up tnt or knowledge TextField + The JTextField is extended from the JComy class. The JTextField allows us to add a single l text. + The syntax of using JTextField is - STextField(); ‘STextField{int col_val); JTextField(String s,int col_val); STextField| String s); Java Program|TxtFieldProg.java) import javacawt import javex.swing.*; - javac TxtFieldProg.java F:\SwingProg> AppletViewer TxtFieldProg java, ‘The Applet Viewer will display the GUI as follows - Output Program Explanation To place the textfield control on the GUI we have followed following steps - 1. Using the getContentPane method an object for the Container class is created. This object is taken in the variable contentPane. 2. The Layout is set using the contentPane object by the statement contentPane.setLayout(new FlowLayout()); ‘The default layout is FlowLayout but you can set other layout managers such as GridLayout, BorderLayout and soon. 3. After setting the layout manager, the TextField component can be created and.placed using add method. In above program, we have created two text fields. In the first text field, the string “Hello” is already written during its creation but the second textfield is kept blank and some string can be written into it during the execution. [225] combo Boxes * JList and JCombobox are very similar components Dut the JList allows to select multiple selections whereas the JCombobox allows only one selection ata time, 5 * Acombo box is a combination of text field and the top down list. The JComboBox is a subclass of class, 2-7 Java Program[ComboBoxProg java) import import java.awtevent.*; import javax.swing.* r ‘javac ButtonProgjava |\SwingProg> Applet Viewer ButtonProg java and you will get the applet as follows - Output Program Explanation The above program, is inherited from the JApplet class. In the init method, we have written the code - 1. Create a container object by using the getContentPane method. This object is now in the variable contentPane. : ° 2. A layout manager such as FlowLayout is used to set the layout of the GUI. 3. The button components are then placed on the GUI using the add method. ‘Adoanced Java [E32] checkbox t the immediate superciass 2-10 re associated with some images using ImagelCon 4, These push buttons a s toon aes pased a argent. Ths oesponding image 6s aPC ead Saas This is necessary to handle the events. 5, Wehave associated an ActionListener ‘event with this program. ae pa essed. We have associated some oe aca oe tActionCommand method. The event handler can be sed. This can be done using se idles eae i i istener(this). When this a call to this method is given the invoked using the methods addActionl s dis gi control goes to the function actionPerfomed. In this method we are simply displaying the appropriate command string in the textbox. «The Check Box is also implementation of AbstractButton class. But JCheckBox is JToggleButton. + The JCheckBox supports two states true or false. » We can associate an icon, string or the state with the checkboxes. The syntax. for the Check Box will be- JCheckBoxitcon ic); ‘ICheckBox{Icon ic, boolean state); ‘ICheckBox(String 8}; - ‘JCheckBox(String ,boolean state); JCheckBox(String s,Icon ic,boolean state); + Following program illustrates the use of check box - Java Program[CheckBoxProg java] import java.awt. import java.awt.event."; import javax.swing.*; r ‘ "7 public class TabbedPaneDemo extends JApplet { public void init() { . ‘STabbedPane mytpane = new JTabbedPane(); Adding the folders on the mytpane.addTab(‘Laptop’, new LaptopPanel()); tabbed pane mytpane.addTab("Os", new OSPanel()); mytpane.addTab(‘Database’, new DatabasePanel()); mytpane.addTab(‘Languages", new LangPanel()); getContentPane().add(mytpane); } 1 ae clase LaptopPanel extends JPanel’ iEspioy Compan ceived { ee LaptopPanel() RadioButton jtb1 = new JRadioButton("DELL"); . add(jrb1); RadioButton jrb2 = new: JRadioButton("Samsung’); edid(jrb2); SRadioButton jeb3 = new JRadioButton("HP"); { Advanced Java Programming ae | add(jrb3); JRadioButton jtb4 = new JRadioButton("Acer’); f add(jrb4); ButtonGroup bg=new ButtonGroup(); bg.add(jrb4); } } defined class OSPanel extends JPanel OS Component { Public OSPanel() { ‘ JComboBox jcb = new JComboBox(); icb.addltem(Windows XP"; jcb.additem(Windows Vista"); icb.additem("Windows 7); icb.addltem(Ubuntu’); Bae add{jeb); } } class DatabasePanel extends JPanel { Public DatabasePanel() { ‘JCheckBox chi = new JCheckBox(‘Oracle'); add(cb1); 7 ‘SCheckBox cb2 = new JCheckBox("MySOL.); add(cb2); 5 ‘SCheckBox cb3 = new JCheckBox("Microsoft Acces add(cb3); } } ss LangPanel extends JP Lany a j9Panel extends JPanel. segetase Component public LangPanel() { ‘Button bi = new JButton(JSP%, add(b1); \JButton b2 = new JButton(‘asP'); add(b2); \JButton bS = new JButton(PHP", add(b3); Database Component defined foc Jo Pragroing 2.4.2] Scroll Pane * The scroll pane is a rectangular areas in which some component can be placed. + The component can be viewed with the help of horizontal and vertical scroll bars. © Using the JScrolIPane class the component can be added in the program. ‘+ “The JScrollPane class extends the Component class. © There are three constructors that can be used for this component - ‘JScrollPane(Component component) JScrollPane(int vscrollbar, int hscrollbar) JScrollPane(Component component, int vscrollbar, int hscrollbar) The component represents the reference to the component. The scrollbar and hscrollbar are the integer values forthe vertical and horizontal scroll bars. These values can be defined by the constants such as . Followingisa simple program which illustrates the use of scrollpane. Step 1: Create a label ‘Step 2: Create a panel Step 3: Use an image with the help of label ‘Step 4: Add the label on the panel Step 5: Create a content pane. Advanced java Programming 2-16 Step 6 : Create a scrollpane component by passing the image (within a panel) as a component to it. ‘Step 7 : Add the the scrollpane component to the content pane component. Java Program import java.awt.*; import javax.swing.*; r ‘ ” Public class ScrollPaneDemo extends JApplet { Public void init() { Container contenitPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel mypanel = new JPanel(); JLabel Li = new JLabel(); Imagelcon i = new Imagelcon("img jpg’); L1.setLocation(20, 100); LA.setSize(120, 120), Li setlcon(i); mypanel.add(L1); int vecrolbar = ScrollPaneConstants. VERTICAL, -SCROLLBAR_AS_NEEDED; int hcrollber = ScrollPaneConstants, HORIZONTAL_SCROLLBAR AS NEEDED; ‘ScrollPane jsp = new JScroliPano(mypanel, vecrollbar, hscrolibar); contentPane.add(jsp, BorderLayout.CENTER); Output Atoanced Jaca 2-17 Swings. [243] Trees «Tree is a type of component that gives the hierarchical view of data. User can expand or shrink the nodes of the tree. Inswing the trees are implemented using the JTree class. This class extends the JComponent. The most commonly used constructor for this class is - JTree(TreeNode root) ‘The root represents the root node of the tree. ‘Using the DefaultMutableTreeNode, it creates a tree node with no root node, the child of root node, specified by user object and it allows only children that have to be specified. It takes boolean types values either ‘true’ or ‘false’. If you will take ‘true’ that means children node are allowed. Step 1: Make use of applet for implementation of the tree program Step 2; Create a tree with root, child and grand child nodes. Step 3: Create a content pane object. Stop 4: Add the JTree component on the content pane. Java Program import javax.swing.*; import java.awt."; import javax.swing.tree. r javac TreeDemo,java D:\JavaPrograms> AppletViewer TreeDemo,java ‘The colummheader denotes the header for each coh lumn, Following isa simple program that shows the use of JTable com, ‘ Tecnica Peat Arop trial ev Advanced Java Programming 2-19 Example Program import javax.swing.*; import java.awt.*; import javax.swing.tree.*; r tf public class TableDemo extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); final String|] th = { "Name’, ‘City’, 'Salary',"Designation" }; final Object!][] mytable = { {"Amun’, ‘Pune’, "5000","Accountant"}, { ‘Archana’, "Mumbai', "7000","Executive'}, { 'Shivani, "Banglore", "10000","Manager'}, { 'Priyanka’, "Chennai, "8000',"Programmer'}, { "Monika’, "Hyderabad", "10000',"Designer"}, {"Shilpa’, "Hyderabad, "12000","Director’}, { “Anuja’, "Delhi", "17000","Director"}, { ‘Kumar’, 'Pune', "10000","Manager"} k JTable table = new JTable(mytable,th); int vacrollbar = ScrollPaneConstants. VERTICAL_SCROLLBAR_AS_NEEDED; int hscrollbar = ScrollPaneConstants. HORIZONTAL_SCROLLBAR_AS_NEEDED; JScroliPane mypane = new JScrollPane(table, vscrollbar, hscrollbar); yonemPane adtmypane, BorderLayout.CENTER); } Following commands are used to display the output javaPrograms>javac TableDemo,java PMevePrograms>AppletViewer TableDemo,java iececutve | [Monika Hyderabad (10000__[Oesigner_| [Snipa [Hyderabad [12000 Ex.24.1: Write a Java Program to display the 3 X3 magic square using JTable Sol.: import javax.swing. import java.awt.*; import javax.swing.tree.*; r v7 Public class TableDemo extends JApplet { . Public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); final Stringl] th = {",","); final Object{][] mytable = { {°4", "9'2"} k JTable table = new JTable(mytablo,th); int vecrolibar = ScrollPaneConstants. -VERTICAL_SCRO} : SCROLL, int hscrollbar = ScrollPaneConstants Hi 'AR_AS_NEEDED; JScrolPane mypane = new JScrolPane(table, vsc », Vacrolibar, hs ); contontPane.add(mypane, BorderLayout. CENTER), erolibar); Progress Bar «Progress bar is used to display the progress of the task. + Itis normally used while creating a GUI for downloading or transferring of file. ‘+ Inswing we use JProgressBar class for creating the progress bar. Constructor Public class ProgressBarProg extends JFrame { ‘Static JFrame frame; ‘Static ProgressBar pbar; ee static void main(String!) args) frame =new JFrame(‘Progress Bar Demo’), Pbar=new JProgressBar(0,2000); _, Phar setBounds(60,50,150,30); Pbar.setValue(0); Phar setStringPainted(true); = Technical Publications" -An up thrust fo knowtedge Adcanced Java Programming 4 frame.add{pbar); frame.setLayout(null); frame.setSize(300,300); frame.setVisible(true); : frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ‘AllBar(); public static void fillBar() { + + int i=0; ty { while(i<=2000) { pbar.setValue({}; ‘Thread.sloep(1000); ini+20; + } ‘catch(Exception 6) 0 How to run above program? . Open command prompt window and type the following command DA>javac ProgressBarProg,java DA>java ProgressBarProg Adoanced Java Programming 2523) (2) Then a progressbar component is created with minimum value 0 to maximum value 2000, Swings. (8) Using setValue(0) we set the initial value of the progress bar to be 0. The setStringPainted(true) method allows to display the progress string. (4) The user defined function fillBar() is created t6 display proceeding of the value in the progress bar.Note that the thread is used to display the progress periodically.The Thread.sleep(1000) is useful in displaying the data after periodic interval. Also note that when we use Thread.sleep function we must use try ...catch block within which this function can be invoked. 2.4.6 | ToolTips Java Program|Too!TIpProg Java] import java.awt.*; import javax.swing.*; public class ToolTipProg { public static void main(Stringl] args) { y + Ucreating frame JFrame frame =new JFrame("Tool Tip Demo"); /[creating label ‘name’ JLabel L=new JLabel(‘Name:"); /[creating Textfield ‘JSTextField T=new JTextField("",10); H[setting tooltip for text box T.sotToolTipText("Enter your Name"); Hereating button JButton B=new JButton("Submit’); Isetting tooltip for button B.setToolTipText('Click to Submit’); /setting layout frame.setLayout(new FlowLayout()); adding Lable, Textfield and button one by one on the frame frame.add(L); frame.add(T); frame.add(B); frame.setSize(300,250); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); How to run above program ? Open command prompt window and type the following command DA>javac ToolTipProg.java DA> java ToolTipProg Advanced Java Programming Program Explanation : Just refer the comment statements provided at each line in above program, prograg very easy to understand. f Review Questions 1. Explain JTree, JTable in Swing with examples 2, Explain how to create progressbar using swing [25] mvc architecture ‘The Model View Controller design pattern separates a software component into three distinct Pieces : a model, a view and a controller, Adeancd aoa Programming « For the button component the color, the size of the button will be decided by the view. + The controller is for managing the user interaction with the model. It is basically for handling the user input. The controller takes care of mouse and keyboard events. For example - For the button component the reaction of events on the button press will be decided by the controller. + The MVC architecture of swing specifies how these three Objects (Model, View and Controller) interact. + For the text field the model is nothing but the conients of the text field. The model must implement the method to change the contents and to discover the contents. For example text model had methods to add, to remove the characters. One important thing to note is that the model is completely non visual. + For a single model there can be more than one views. Each view can show different aspect of the content. For example - A particular web page can be viewed in its WYSIWYG (What-You-See-Is-What- You-Get) form or in the raw tagged form. But there are some components like button for which it is not possible to have multiple views for the same model. + The controller handles the user-input events such as mouse clicks and keyboard strokes. On receiving the events the controller decides whether to translate it into corresponding model or in views. + If user presses the button then the controller calls the event handling methods in order to handle the button press. The controller tells the view to update itself and to display: the desired result. For displaying the desired result the view reads the content from the model. Thus model-view and controller works together in order to accomplish the certain task. at Review Question 1. Writea short note on - MVC Architecture 2-25 Swings Multiple Choice Questions. 2 Q1 Pluggable look and feel and lightweight components are the features supported by __. [a]swing [b]awr [e]Core Java dd] None of these Q2 Swing is based on ___ architecture client server (b] model view controller [c}layered d]none of these Q3 Swing is not a part of JFC(Jjava Foundation Classes) that is used to create GUI application [a] True [b] False Q4 The Java Foundation Classes (FC) is a set of GUI components which simplify the development of desktop applications. [a] True [b) False Q5 Following letter used as a prefix to swing component. fla [Js Ss fa is one of the features of object oriented programming that allows the creation of hierarchical classifications. a6 [a]Polymorphism — [b] Class inheritance 'd] Object Q.7 In Swing JButton class is derived from ____- [a] AbstractButton [6 ]JToggleButton c]JComponent — [d] None of these Q8 The JTextComponent derives two components JTextField and __ [a] JComboBox b]JTextArea [c]JSlider dJ All of the above Q.9_ In Swing class hierarchy the class present at the rootis__. [2] Component [b] Window [ce] Container [d] Object ato pane can be used to add component to container [a]ciass b] Content [e] Container [d] All of above Q.11 Select the correct source code using swing for generating following output. in up thrust for knowledge

You might also like