All the Lectures of Java II

  • Lecturer:   Ms. Shumaila Bashir
  • Subject Title:   JAVA II
  • Code:   ITC-505

  • Lecture No:   1
    Date:   27/05/2013

    INTRODUCTION Software applications have become extremely user-friendly with the introduction of graphics in user interface. Languages are now having graphical objects that can be controlled by the developers as well as user. One of the most important outcomes of this is that languages are now based on Graphical User Interface (GUI). Java is one of these languages that support GUI objects to create graphical user interface applications. GRAPHICAL USER INTERFACE (GUI) A GUI is an interface through which user can interact with system in friendly manner. A GUI varies from application to application, and may consist of textboxes, labels, buttons, list boxes, and other such elements. A GUI component is a visual object. The user interacts with these objects with the mouse or keyboard. Different programming languages provide different ways of creating GUIs. A GUI element is generally created using the following procedure. Create an element, instance , check box, label or button. Determine its initial appearance. Decide whether it should occupy a specific position. Add it to the screen interface. GRAPHICAL USER INTERFACE (GUI) In java, any operation that is common to all the GUI components is found in the class component. In java, to create these GUI components we need to use the classes that are available in the java.awt or javax.swing package. AWT stands for Abstract Windowing Toolkit. AWT is set of java classes that allow us to create a GUI, and accepts user inputs through the keyboard or mouse. The AWT provides various items to create an attractive and efficient GUI. The AWT package consists of classes , interfaces, and other packages . The next slide shows figure thats describe a portion of the AWT class hierarchy. AWT CLASS HIERARCHY SWING PACKAGE when java was introduced, AWT was the only available graphical user interface (GUI). AWT components were considered as heavy components. Today, however java offers lightweight components. Sun Microsystems, a company that developed java, was working on a project called �Swing� when they developed the light weight components. Hence, the lightweight user interface components are called �Swing Components�. Swing is a component of the Java Foundation Class (JFC). It is an improvement over the AWT component. JAVA FOUNDATION CLASS (JFC) Before the creation of swing components, it is very difficult to create a true abstract system that works in the same manner on all systems. For example, different systems report mouse movement differently, and GUI elements such as buttons, look different on various platforms. Programmer found it difficult to write an AWT system for one platform with the same look and feel on other platforms. They needed to do lot of testing before creating applications. Thus, software needed a new system to address this problem. Sun Microsystems solution to this problem was JFC (Java Foundation Class). The JFC system completely relies on the �container� and �Frame� components. BENEFITS OF SWING COMPONENTS Some of the benefits of using Swing components are: More efficient use of resources: Lightweight components are really "lighter" than heavyweight components. More consistency across platforms because Swing is written entirely in Java. Cleaner look-and-feel integration: You can give a set of components a matching look-and-feel by implementing them using Swing. The Swing package also consists of classes , interfaces, and other packages . Next Slide shows figure that describes a portion of the Swing class hierarchy. SWING CLASSES HIERARCHY



    Lecture No:   2
    Date:   27/05/2013

    DIFFERENCE BETWEEN AWT AND SWING COMPONENTS The Abstract Window Toolkit (AWT) and Swing provide standard components to build a graphical user interface (GUI) The major difference between AWT and Swings is AWT is heavy weight component nothing but it is based on operating system. but the swings are light weight components, this is the independent of operating system. SWING is an extension of AWT..... having advance controls and with extra features of previously present controls. E.g Swing provides some advanced component like JTree, JTabbedPane, JList and many more. A lightweight component can have transparent pixels; a heavyweight is always opaque. 4) A lightweight component can appear to be non-rectangular because of its ability to set transparent areas; a heavyweight can only be rectangular. 5) Swing components provide dynamic look and feel whereas awt components provide static look and feel. 6) Another difference is that Swing is pure Java, and therefore platform independent. Swing looks identically on all platforms, while AWT looks different on different platforms. 7)AWT is heavy weight components which take time for loading. Swing is light weight components which take more time for first time loading after then its uses already loaded components. so that swing is faster than awt components. Mixing heavy weight and light weight components Most of the issues related to mixing AWT and Swing components are related to the mixing of so-called heavyweight and lightweight components. AWT is so called heavyweight components and have their own viewport which sends the output to the screen. Where as, Swing is ligthweight components and does not write itself to the screen, but redirect it to the component it builds on. Heavyweight components also have their own z-ordering. This is the reason why you can't combine AWT and Swing in the same container. If you do, AWT will always be drawn on top of the Swing components. You can combine AWT and Swing, just don't do it in the same container (e.g. panel, groupbox, etc.) and don't put a heavyweight component inside a lightweight. When a lightweight component overlaps a heavyweight component, the heavyweight component is always on top, regardless of the relative z-order of the two components.



    Lecture No:   3
    Date:   29/05/2013

    JAVA SWING PACKAGE Javax.swing package: In swing package, there are 256 predefine classes and 75 interfaces used to create an advance GUI applications. Swing package have more graphics components than awt. Container A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container. Top-Level Containers Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet. When using these classes, you should keep these facts in mind: To appear onscreen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI. You can optionally add a menu bar to a top-level container. The menu bar is by convention positioned within the top-level container The JComponent Class JComponent is a predefine class of java swing package, it is super or parent class of swing components. All Swing components whose names begin with "J" descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent. However, JFrame and JDialog don't because they implement top-level containers. The JComponent class extends the Container class, which itself extends Component. The Container class has support for adding components to the container and laying them out. JFrame Component: A JFrame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. JFrame Features It’s a window with title, border, (optional) menu bar and user-specified components. It can be moved, resized, iconified. It is not a subclass of JComponent. By default JFrame is appear at the top left corner of screen. JFrame is by default invisible. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane. JFrame Constructors To create a Frame you must create an instance of JFrame class by using one of the following contructors: JFrame() Constructs a new frame that is initially invisible.   JFrame(GraphicsConfigurationgc) Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.   JFrame(String title) Creates a new, initially invisible Frame with the specified title.   JFrame(String title, GraphicsConfigurationgc) Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device. Example N0.1 JFrame Methods Change the location of JFrame: By default, a Jframe is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y). Setting an Icon for a Frame in Java frame.setIconImage(Toolkit.getDefaultToolkit().getImage("icon_name.gif")); Removing the Title Bar of a Frame frame.setUndecorated(true); Making a Frame Non Resizable in Java frame.setResizable(false); Making a Frame visible on screen: JFrame.setVisible(true); Change the size of JFrame: JFrame.setSize(int height, int width); getContentPane(); to add components in a Frame we must add it in a contentpane by using JFrame.getContentPane() method. JFrame.pack(); This method is used to pack all the components of JFrame. Pack() method is used to fix the size of JFrame according to the components its contain. JWindow java.lang.Object java.awt.Component java.awt.Container java.awt.Window javax.swing.JWindow   A JWindow is a container that can be displayed anywhere on the user's desktop. It does not have the title bar, window-management buttons, or other trimmings associated with a JFrame Constructors: JWindow() Creates a window with no specified owner. JWindow(Frame owner) Creates a window with the specified owner frame. JWindow(GraphicsConfigurationgc) Creates a window with the specified GraphicsConfiguration of a screen device. JButton A button is a component the user clicks to trigger a specific action.   JButton Constructors JButton() Creates a button with no set text or icon. JButton(Action a) Creates a button where properties are taken from the Action supplied. JButton(Icon icon) Creates a button with an icon. JButton(String text) Creates a button with text. JButton(String text, Icon icon) Creates a button with initial text and an icon A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and image.We use a Swing JLabel when we need a user interface component that displays a message or an image.   JLabel JLabel Constructor JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(Icon image) Creates a JLabel instance with the specified image. JLabel(Icon image, inthorizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(String text, Icon icon, inthorizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, inthorizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. JTextField JTextField allows editing/displaying of a single line of text. JTextField is an input area where the user can type in characters. JTextField Constructor  JTextField() Constructs a new TextField.   JTextField(Document doc, String text, int columns) Constructs a new JTextField that uses the given text storage model and the given number of columns.   JTextField(int columns) Constructs a new empty TextField with the specified number of columns.   JTextField(String text) Constructs a new TextField initialized with the specified text.   JTextField(String text, int columns) Constructs a new TextField initialized with the specified text and columns. Example import java.awt.*; import javax.swing.*; public class Example { public static void main(String[] args) { JFrame f = new JFrame("The Frame"); JButton b1=new JButton("OK"); JButton b2=new JButton("Cancel"); JLabel L1=new JLabel("Name"); JTextField T1=new JTextField(15); Container content = f.getContentPane(); content.setLayout(new FlowLayout()); content.add(L1); content.add(T1); content.add(b1); content.add(b2); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,250); f.setLocation(400,300); f.setVisible(true); }}



    Lecture No:   4
    Date:   03/06/2013

    LECTURE 04 LAYOUTS Layout Manager A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, BoxLayout, GridLayout NullLayout: FlowLayout The elements of a FlowLayout are organized in a top to bottom, left to right fashion. This is the simplest layout manager in the Java Swing toolkit. It is mainly used in combination with other layout managers. The manager puts components into a row. In the order, they were added. If they do not fit into one row, they go into the next one. The components can be added from the right to the left or vice versa. The manager allows to align the components. Implicitly, the components are centered and there is 5px space among components and components and the edges of the container. FlowLayout Constructors: FlowLayout() Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align, int hgap, int vgap) Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. Null Layout We can use no layout manager, if we want. There might be situations, where we might not need a layout manager. To create truly portable, complex applications, we need layout managers. Without layout manager, we position components using absolute values. In java, without manager, we position components by using setBounds() method. setBound(strt Col, strt Row, Ending Col, Ending Row); BorderLayout A BorderLayout manager is a very handy layout manager. It divides the space into five regions. North, West, South, East and Centre. Each region can have only one component. If we need to put more components into a region, we can simply put a panel there with a manager of our choice. The components in N, W, S, E regions get their preferred size. The component in the centre takes up the whole space left. BorderLayout Constructors: BorderLayout() Constructs a new border layout with no gaps between components. BorderLayout(int hgap, int vgap) Constructs a border layout with the specified gaps between components. GridLayout The GridLayout layout manager lays out components in a rectangular grid. The container is divided into equally sized rectangles. One component is placed in each rectangle. The layout manager takes four parameters. The number of rows, the number of columns and the horizontal and vertical gaps between components. E.g: JFrame.setLayout(new GridLayout(5, 4, 5, 5)); GridLayout Constructor   GridLayout() Creates a grid layout with a default of one column per component, in a single row.   GridLayout(int rows, int cols) Creates a grid layout with the specified number of rows and columns.   GridLayout(int rows, int cols, int hgap, int vgap) Creates a grid layout with the specified number of rows and columns. BoxLayout A layout manager that allows multiple components to be laid out either vertically or horizontally. The components will not wrap so, for example, a vertical arrangement of components will stay vertically arranged when the frame is resized. BoxLayout Constructor   BoxLayout(Container target, int axis) Creates a layout manager that will lay out components along the given axis. Example No.1 import java.awt.*; import javax.swing.*; public class BoxLayoutExp extends JFrame { public BoxLayoutExp() { setTitle("Box Layout Example"); setSize(150, 150); getContentPane().setLayout( new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); JButton btn4 = new JButton("Button 4"); getContentPane().add(btn1); getContentPane().add(btn2); btn1.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn3); getContentPane().add(btn4); } public static void main(String[] args) { BoxLayoutExp obj = new BoxLayoutExp(); obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); obj.setVisible(true); } } JPanel: A JPanel is an empty area that can be used either to Layout other components, including other panels. Also used to Draw graphics on. JPanel Constructors   JPanel() Creates a new JPanel with a double buffer and a flow layout. JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout manager



    Lecture No:   5 & 6
    Date:   03/06/2013

    Mix Layout Example: importjava.awt.*; importjavax.swing.*; public class Layout_Panels extends JFrame { voidLP_Method () { Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); p1.add(new JButton("B"), BorderLayout.WEST); p1.add(new JButton("C"), BorderLayout.CENTER); p1.add(new JButton("D"), BorderLayout.EAST); p1.add(new JButton("E"), BorderLayout.SOUTH); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); p2.add(new JButton("G")); p2.add(new JButton("H")); p2.add(new JButton("I")); p2.add(new JButton("J")); p2.add(new JButton("K")); JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); p3.add(new JButton("M")); p3.add(new JButton("N")); p3.add(new JButton("O")); p3.add(new JButton("P")); c.setLayout(new BorderLayout()); c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); c.add(p3, BorderLayout.EAST); pack(); setVisible(true); } public static void main(String[] args) { Layout_Panels LP = new Layout_Panels (); frame.LP_Method(); } } Event Programming  In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.  Event is a package in java AWT package.  If we are going to create an event program so we first import the “java.awt.event package. This package is used for both AWT and Swing Components.  Event package contained different predefine classes, interfaces and methods that are related/ useful for event programming.  Through Event programming we can perform actions on Buttons, TextFields, Checkboxes, and other components of java. Example: importjava.awt.*; importjavax.swing.*; importjava.awt.event.*; public class SwingTest1 extends JPanel implements ActionListener { JLabel L1; Icon I1; JButton B1,B2; JTextField T1; public SwingTest1() { setLayout(new GridLayout(4,1)); I1 = new ImageIcon("f1.jpg"); L1 = new JLabel("Java Swing",I1,JLabel.CENTER); L1.setForeground(Color.black); L1.setToolTipText("Title Label"); T1 = new JTextField(20); T1.setForeground(Color.magenta); //T1.setBackground(Color.blue); T1.setToolTipText("Text field"); B1 = new JButton("Diaplay Message",I1); B1.setMnemonic(KeyEvent.VK_Z); B1.setToolTipText("Diaplay Message"); B1.setForeground(Color.yellow); B1.setBackground(Color.blue); B1.addActionListener(this); B2 = new JButton("Exit",I1); B2.setMnemonic(KeyEvent.VK_B); B2.setToolTipText("Quit"); B2.setForeground(Color.yellow); B2.setBackground(Color.blue); B2.addActionListener(this); add(L1); add(T1); add(B1); add(B2); } public static void main(String S[]) { JFrame F = new JFrame("Testing Frame"); SwingTest1 T = new SwingTest1(); F.getContentPane().add(T); /*F.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent W) { System.exit(0); } });*/ F.setSize(200,200); F.setVisible(true); } public void actionPerformed(ActionEvent A) { if(A.getSource()==B1) T1.setText("Hello, Hi!"); if(A.getSource()==B2) System.exit(0); } } Example No.2 importjavax.swing.*; importjava.awt.event.*; importjava.awt.*; public class calc extends JFrame implements ActionListener { JLabel Val1,Val2,Result; JTextField Valtxt1,Valtxt2,Resulttxt; JButtonaddi,sub,mul,divide,clear,Quit; JPanel p1,p2; JFrame frame; Container content; publiccalc() { content=getContentPane(); Val1 = new JLabel("value1"); Val2 = new JLabel("Value2"); Result = new JLabel("Result"); Valtxt1 = new JTextField(10); Valtxt2 = new JTextField(10); Resulttxt = new JTextField(10); addi = new JButton("+"); sub = new JButton("-"); mul = new JButton("*"); divide = new JButton("/"); clear = new JButton("C"); Quit = new JButton("Q"); addi.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); divide.addActionListener(this); clear.addActionListener(this); Quit.addActionListener(this); addi.setMnemonic(KeyEvent.VK_A); sub.setMnemonic(KeyEvent.VK_S); mul.setMnemonic(KeyEvent.VK_M); divide.setMnemonic(KeyEvent.VK_D); clear.setMnemonic(KeyEvent.VK_C); Quit.setMnemonic(KeyEvent.VK_Q); p1 = new JPanel(); p1.setLayout(new GridLayout(3,2)); p1.add(Val1); p1.add(Valtxt1); p1.add(Val2); p1.add(Valtxt2); p1.add(Result); p1.add(Resulttxt); p2 = new JPanel(); p2.setLayout(new GridLayout(1,6)); p2.add(addi); p2.add(sub); p2.add(mul); p2.add(divide); p2.add(clear); p2.add(Quit); content.setLayout(new GridLayout(2,1)); content.add(p1); content.add(p2); pack(); setVisible(true); } public static void main(String args[]) { newcalc(); } public void actionPerformed(ActionEvent A) { int a = Integer.parseInt(Valtxt1.getText().trim()); int b = Integer.parseInt(Valtxt2.getText().trim()); intRst=0; if(A.getSource()==addi) Rst=a+b; if(A.getSource()==sub) Rst=a-b; if(A.getSource()==mul) Rst=a*b; if(A.getSource()==divide) Rst=a/b; Resulttxt.setText(String.valueOf(Rst)); if(A.getSource()==clear) { Valtxt1.setText(" "); Valtxt2.setText(" "); Valtxt1.requestFocus(true); } if(A.getSource() == Quit) { System.exit(0);}}} JCheckBox Checkboxes are used for selection of options. More than one option (or none) may be selected. JCheckBox() is used to construct these widgets. JCheckBox Constructors: JCheckBox() Creates an initially unselected check box button with no text, no icon. JCheckBox(Icon icon) Creates an initially unselected check box with an icon. JCheckBox(Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. JCheckBox(String text) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon. JCheckBox(String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected. Mix Layout Example: import java.awt.*; import javax.swing.*; public class Layout_Panels extends JFrame { public static void main(String[] args) { Layout_Panels LP = new Layout_Panels (); frame.LP_Method(); } void LP_Method () { Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); p1.add(new JButton("B"), BorderLayout.WEST); p1.add(new JButton("C"), BorderLayout.CENTER); p1.add(new JButton("D"), BorderLayout.EAST); p1.add(new JButton("E"), BorderLayout.SOUTH); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); p2.add(new JButton("G")); p2.add(new JButton("H")); p2.add(new JButton("I")); p2.add(new JButton("J")); p2.add(new JButton("K")); JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); p3.add(new JButton("M")); p3.add(new JButton("N")); p3.add(new JButton("O")); p3.add(new JButton("P")); c.setLayout(new BorderLayout()); c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); c.add(p3, BorderLayout.EAST); pack(); setVisible(true); } } Event Programming  In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.  Event is a class of AWT package.  If we are going to create an event program so we first import the “java.awt.event package. This package is used for both AWT and Swing Components.  Event package contained different predefine classes, interfaces and methods that are related/ useful for event programming.  Through Event programming we can perform actions on Buttons, TextFields, Checkboxes, and other components of java.  GUI systems handle all user Example: import java.awt.*; importjavax.swing.*; importjava.awt.event.*; public class SwingTest1 extends JPanel implements ActionListener { JLabel L1; Icon I1; JButton B1,B2; JTextField T1; public SwingTest1() { setLayout(new GridLayout(4,1)); I1 = new ImageIcon("f1.jpg"); L1 = new JLabel("Java Swing",I1,JLabel.CENTER); L1.setForeground(Color.black); L1.setToolTipText("Title Label"); T1 = new JTextField(20); T1.setForeground(Color.magenta); //T1.setBackground(Color.blue); T1.setToolTipText("Text Area"); B1 = new JButton("Diaplay Message",I1); B1.setMnemonic(KeyEvent.VK_Z); B1.setToolTipText("Diaplay Message"); B1.setForeground(Color.yellow); B1.setBackground(Color.blue); B1.addActionListener(this); B2 = new JButton("Bye Bye",I1); B2.setMnemonic(KeyEvent.VK_B); B2.setToolTipText("Quit"); B2.setForeground(Color.yellow); B2.setBackground(Color.blue); B2.addActionListener(this); add(L1); add(T1); add(B1); add(B2); } public static void main(String S[]) { JFrame F = new JFrame("Testing Frame"); SwingTest1 T = new SwingTest1(); F.getContentPane().add(T); F.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent W) { System.exit(0); } }); F.setSize(200,200); F.setVisible(true); } public void actionPerformed(ActionEvent A) { if(A.getSource()==B1) T1.setText("Hello, Hi!"); if(A.getSource()==B2) System.exit(0); } } Example No.2 importjavax.swing.*; importjava.awt.event.*; importjava.awt.*; public class calc extends JFrame implements ActionListener { JLabel Val1,Val2,Result; JTextField Valtxt1,Valtxt2,Resulttxt; JButtonaddi,sub,mul,divide,clear,Quit; JPanel p1,p2; JFrame frame; Container content; publiccalc() { content=getContentPane(); Val1 = new JLabel("value1"); Val2 = new JLabel("Value2"); Result = new JLabel("Result"); Valtxt1 = new JTextField(10); Valtxt2 = new JTextField(10); Resulttxt = new JTextField(10); addi = new JButton("+"); sub = new JButton("-"); mul = new JButton("*"); divide = new JButton("/"); clear = new JButton("C"); Quit = new JButton("Q"); addi.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); divide.addActionListener(this); clear.addActionListener(this); Quit.addActionListener(this); addi.setMnemonic(KeyEvent.VK_A); sub.setMnemonic(KeyEvent.VK_S); mul.setMnemonic(KeyEvent.VK_M); divide.setMnemonic(KeyEvent.VK_D); clear.setMnemonic(KeyEvent.VK_C); Quit.setMnemonic(KeyEvent.VK_Q); p1 = new JPanel(); p1.setLayout(new GridLayout(3,2)); p1.add(Val1); p1.add(Valtxt1); p1.add(Val2); p1.add(Valtxt2); p1.add(Result); p1.add(Resulttxt); p2 = new JPanel(); p2.setLayout(new GridLayout(1,6)); p2.add(addi); p2.add(sub); p2.add(mul); p2.add(divide); p2.add(clear); p2.add(Quit); content.setLayout(new GridLayout(2,1)); content.add(p1); content.add(p2); pack(); setVisible(true); } public static void main(String args[]) { newcalc(); } public void actionPerformed(ActionEvent A) { int a = Integer.parseInt(Valtxt1.getText().trim()); int b = Integer.parseInt(Valtxt2.getText().trim()); intRst=0; if(A.getSource()==addi) Rst=a+b; if(A.getSource()==sub) Rst=a-b; if(A.getSource()==mul) Rst=a*b; if(A.getSource()==divide) Rst=a/b; Resulttxt.setText(String.valueOf(Rst)); if(A.getSource()==clear) { Valtxt1.setText(" "); Valtxt2.setText(" "); Valtxt1.requestFocus(true); } if(A.getSource() == Quit) { System.exit(0);}}} JCheckBox Checkboxes are used for selection of options. More than one option (or none) may be selected. JCheckBox() is used to construct these widgets. JCheckBox Constructors: JCheckBox() Creates an initially unselected check box button with no text, no icon. JCheckBox(Icon icon) Creates an initially unselected check box with an icon. JCheckBox(Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. JCheckBox(String text) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon. JCheckBox(String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected.



    Lecture No:   7
    Date:   6/06/2013

    Lecture 07 JCheckBox Checkboxes are used for selection of options. More than one option (or none) may be selected. JCheckBox() is used to construct these widgets. JCheckBox Constructors: JCheckBox() Creates an initially unselected check box button with no text, no icon. JCheckBox(Icon icon) Creates an initially unselected check box with an icon. JCheckBox(Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. JCheckBox(String text) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon. JCheckBox(String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected. Example No: 01 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class CheckboxExample extends JFrame implements ItemListener { JCheckBox cb1=new JCheckBox("One"); JCheckBox cb2=new JCheckBox("Two"); JCheckBox cb3=new JCheckBox("Three"); JTextField t1=new JTextField(15); JPanel P1=new JPanel(); JPanel P2=new JPanel(); CheckboxExample() { P1.add(t1); P2.setLayout(new BoxLayout(P2,BoxLayout.Y_AXIS)); cb1.addItemListener(this); cb2.addItemListener(this); cb3.addItemListener(this); cb1.setBackground(Color.pink); cb2.setBackground(Color.red); cb3.setBackground(Color.green); cb1.setToolTipText("One"); cb2.setToolTipText("Two"); cb3.setToolTipText("Three"); cb1.setMnemonic(KeyEvent.VK_O); cb2.setMnemonic(KeyEvent.VK_T); cb3.setMnemonic(KeyEvent.VK_E); P2.add(cb1); P2.add(cb2); P2.add(cb3); setLayout(new GridLayout(2,1)); add(P1); add(P2); } public static void main(String[] args) { CheckboxExample f=new CheckboxExample(); f.setVisible(true); f.pack(); f.setDefaultCloseOperation(3); } public void itemStateChanged(ItemEvent a) { if(a.getSource()==cb1) { if(a.getStateChange()==a.SELECTED) t1.setText("One"); else if(a.getStateChange()==a.DESELECTED) t1.setText(""); } else if(a.getSource()==cb2) { if(a.getStateChange()==a.SELECTED) t1.setText("Two"); else if(a.getStateChange()==a.DESELECTED) t1.setText(""); } else if(a.getSource()==cb3) { if(a.getStateChange()==a.SELECTED) t1.setText("Three"); else if(a.getStateChange()==a.DESELECTED) t1.setText(""); }}} Class Font java.lang.Object java.awt.Font A class that produces font objects. Font Constructor: public Font(String name, int style, int size) Creates a new font with the specified name, style and point size. Parameters: name - the font name (Serif,scanSerif) style - the constant style used (BOLD,ITALIC,or PLAIN) size - the point size of the font (Font size: ) Following statement shows how to create an object of Font Class: Font f=new Font(“Serif”, Font.BOLD,14); Example:



    Lecture No:   8
    Date:   6/06/2013

    JAVA II (ITC-505) Lecture 08 JList JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener. JList Constructors JList() Constructs a JList with an empty model. JList(ListModeldataModel) Constructs a JList that displays the elements in the specified, non-null model. JList(Object[] listData) Constructs a JList that displays the elements in the specified array. JList(Vector listData) Constructs a JList that displays the elements in the specified Vector. JComboBox Java Swing Tutorial Explaining the JComboBox Component.JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists. JComboBox Constructor JComboBox() Creates a JComboBox with a default data model. JComboBox(ComboBoxModelaModel) Creates a JComboBox that takes it’s items from an existing ComboBoxModel. JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array. JComboBox(Vector items) Creates a JComboBox that contains the elements in the specified Vector. Example of JList and JComboBox import java.awt.*; importjava.awt.event.*; importjavax.swing.*; importjavax.swing.event.*; public class SwingTest2 extends JPanel implements ListSelectionListener, ActionListener { JLabelcombolabel,listlabel; JPaneljp; JComboBoxcb; JListjl; JScrollPanesp; public SwingTest2() { setLayout(new GridLayout(2,2)); String caption[]={"Orange","Banana","Mango","Apple","Watermelon"}; combolabel= new JLabel(); listlabel=new JLabel(); cb=new JComboBox(caption); jl=new JList(caption); jl.setVisibleRowCount(5); cb.addActionListener(this); jl.addListSelectionListener(this); JScrollPane pa=new JScrollPane(jl); pa.setViewportView(jl); add(cb); add(jl); add(combolabel); add(listlabel); } public void actionPerformed(ActionEventae) { if(ae.getSource()==cb) combolabel.setText(""+cb.getSelectedItem()); } public void valueChanged(ListSelectionEvent e) { if(e.getSource()==jl) listlabel.setText((String)jl.getSelectedValue()); } public static void main(String args[]) { JFramejf= new JFrame("combo and list example"); SwingTest2obj=new SwingTest2(); jf.getContentPane().add(obj); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.pack(); jf.setVisible(true); Example 2: import java.awt.*; importjava.awt.event.*; importjavax.swing.*; importjava.util.*; public class JListExample extends JFrame implements ActionListener { JList list; Vector listData; JTextFieldtextfield; JButtonaddButton; JButtonremoveButton; public static void main(String[] argv) { JListExamplemainApp = new JListExample(); } publicJListExample() { super("JList Example"); setBounds(0, 0, 450, 350); getContentPane().setLayout(null); setDefaultCloseOperation(EXIT_ON_CLOSE); // Create the list object... list = new JList(); list.setBounds(10, 10, 420, 200); listData = new Vector(); // Create a JTextField... textfield = new JTextField(15); textfield.setLocation(10, 220); textfield.setSize(textfield.getPreferredSize()); // Create the two buttons... addButton = new JButton("Add Text to List"); addButton.setLocation(200, 220); addButton.setSize(addButton.getPreferredSize()); removeButton = new JButton("Remove Selected from List"); removeButton.setLocation(200, 250); removeButton.setSize(removeButton.getPreferredSize()); // Add the action listeners... addButton.addActionListener(this); removeButton.addActionListener(this); // Add the objects to the content pane... getContentPane().add(list); getContentPane().add(textfield); getContentPane().add(addButton); getContentPane().add(removeButton); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource() == addButton) { // Check there is text in the 'textfield' if(textfield.getText().compareTo("") != 0) { // Then add it to the JList object listData.add(textfield.getText()); list.setListData(listData); // Clear the textfield... textfield.setText(""); } } else if(e.getSource() == removeButton) { // Check there is a list item selected if(list.getSelectedValue() != null) { // Then add it to the JList object listData.remove(list.getSelectedValue()); list.setListData(listData); } } }}