Você está na página 1de 36

JAVA AWT PACKAGES The Abstract Window Toolkit(AWT) package in java contains set of classes that enables the

user to create Graphical User Interface Applications.( The user interface is that part of a program that interacts with the user of the program) It also provides the facility of receiving user input from mouse and keyboard. The AWT helps to implement common window based tasks such as adding buttons, textboxes, scrollbars etc. Components and containers A graphical user interface is built of graphical elements called components. Typical components include such items as buttons, scrollbars, and text fields. Components allow the user to interact with the program and provide the user with visual feedback about the state of the program. Components do not stand alone, but rather are found within containers. Containers contain and control the layout of components. Containers are themselves components, and can thus be placed inside other containers. Components must fit completely within the container that contains them Types of Components

Component class is the super class to all other classes from which various GUI elements are realized. Types of containers The AWT provides four container classes. They are class Window and its two subtypes -class Frame and class Dialog -- as well as the Panel class. In addition to the containers provided by the AWT, the Applet class is a container -- it is a subtype of the Panel class and can therefore hold components. Brief descriptions of each container class provided by the AWT are provided below.

Window A top-level display surface (a window). It just specifies the layout of the window. The Window class has no border and no title.

Frame A top-level display surface (a window) with a border and title. An instance of the Frame class may has a title bar, menu bar and resizable border. A frame can be created by the statement Frame f=new Frane(Frame Window) After the window is created, it must be displayed by calling setVisible( ) The window can be sized by calling resize()

Dialog It is popup window that is used to accept input from user or to display any messages. An instance of the Dialog class cannot exist without an associated instance of the Frame class. A dialog can be created using the following statement Dialog d=new Dialog(frame, Title of dialog,true);

Panel It is container for holding components like buttons,text fields etc Panels are used for organizing components. Each panel can have a different layout. A panel is created using the following constructor Panel p=new Panel(); Once the panel is created, it should be added to a window, a frame or an applet using add() method

AWT Components AWT components are used to accept data from the user. AWT components like buttons and textboxes makes data entry easier. Components can work when they are added to a container. The AWT has following components (a) Labels Labels are used to display non editable text. Most of the times label is used to demonstrate the significance of the other parts of the GUI. A label is created as Label label1=new Label(string); Label label2=new Label(string,int); Eg:

import java.awt.*; import java.applet.*; //<applet code="MyLabel" width=300 height=300> //</applet> public class MyLabel extends Applet { public void init() { Label l1=new Label("Label One"); Label l2=new Label("Label Two",l1.RIGHT); add(l1); add(l2); } } (b) Buttons Buttons are used to trigger events in GUI environment. The button class is used to create a button. A button is created as Button b1=new Button(String); Here String is the label given to the button import java.awt.*; import java.applet.*; //<applet code="button" width=300 height=300> //</applet> public class button extends Applet { public void init() { Label l1=new Label("Do you want to continue"); Button b1=new Button("YES"); Button b2=new Button("NO"); add(l1); add(b1); add(b2); } }

(c) Text Fields and Text Areas

The Text Field and Text Area classes are used to accept data from a user. The text fueld handles single line of text, whereas the text area handles multiple lines of text. Syntax TextField t1=new TextField(); TextField t2=new TextField(string); TextField t3=new TextField(string,int); The first statement creates an empty text field. The second creates a text field with the specified string. The third statement creates a text field with the specified string and specified width. Eg; TextField t3=new TextField(Sample text,20) TextField class provides the following methods getText() -> Returns the text in field setText(string) -> Fills the field with the string setEditable(boolean) -> makes the field editable, if true is passed as an argument import java.awt.*; import java.applet.*; //<applet code="TextField" width=300 height=300> //</applet> public class TextField extends Applet { public void init() { TextField t = new TextField("Enter your text here"); add(t); t.setText("Enter your text here"); } } The Text Areas are ditable text having more than one line of input. Syntax TextArea t1=new TextArea(); TextArea t2=new TextArea(rows,characters); TextArea t3=new TextArea(string); TextArea t4=new TextArea(string, rows,characters);

Eg: TextArea t1=new TextArea(); TextArea t2=new TextArea(6,40); TextArea t3=new TextArea(Sample Text); TextArea t4=new TextArea(Sample Text,6,40); (d) Checkboxes Checkboxes are labeled or unlabelled boxes that can be either checked off or empty. Syntax Checkbox c1=new Checkbox(string); Eg; import java.awt.*; import java.applet.*; //<applet code="checkbox" width=300 height=300> //</applet public class checkbox extends Applet { public void init() { Checkbox c1 = new Checkbox("Windows xp"); Checkbox c2 = new Checkbox("Windows 98"); Checkbox c3 = new Checkbox("Windows 95"); add(c1); add(c2); add(c3); } } (e)Radio Buttons(Check box groups) Checkboxes can be organized into groups so that one of them can be checked at a time. These checkboxes are often called radio buttons. Syntax CheckboxGroup cg=new Checkbox Group Eg; import java.awt.*; import java.applet.*; //<applet code="radio" width=300 height=300>

//</applet public class radio extends Applet { public void init() { CheckboxGroup cg= new CheckboxGroup(); Checkbox c1 = new Checkbox("Windows xp",cg,false); Checkbox c2 = new Checkbox("Windows 98",cg,false); Checkbox c3 = new Checkbox("Windows 95",cg,false); add(c1); add(c2); add(c3); } } (f) LIST The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items. Syntax List l=new List(3,true); l.add(List1); l.add(List2); l.add(List3); add(l); eg: import java.awt.*; import java.applet.*; //<applet code="list" width=300 height=300> //</applet> public class list extends Applet { public void init() { List l = new List(4,true); l.add("MERCURY"); l.add("VENUS"); l.add("EARTH"); l.add("MARS"); add(l); }

} (g) CHOICE Choice class implements a popup menu with a fixed position. It pops up when the user clicks it. Syntax Choice ch=new Choice(); ch.add(List1); ch.add(List2); ch.add(List3); add(ch); eg: import java.awt.*; import java.applet.*; //<applet code="list" width=300 height=300> //</applet> public class list extends Applet { public void init() { Choice ch = new Choice(); ch.add("MERCURY"); ch.add("VENUS"); ch.add("EARTH"); ch.add("MARS"); add(ch); } }

EVENT HANDLING

An event is said to occur when user clicks a button, types a text, uses a mouse, or perform any other interface related action in an applet. Components of an event 1. Event An event occurs when pressing a button, clicking a menu etc 2. Event source - Object that generates an event eg. button, checkbox etc) 3. Listener- Method that understand the event and process it Delegation Event Model This is the modern approach to handle events, which defines standard and consistent mechanism to generate and process events. In this scheme the listener simply waits until it receives an event. Once received the listener process the event and perform action based on the event. In order to receive an event notification the listener must register with a source. Notification is sent only to listener that wants to receive them. Event handling is implemented with the help of various Event Classes. Listeners are created by implementing one or more interfaces. Event occurs event source invokes methods defined in Listener Interfaces

EVENT SOURCE BUTTONS,LIST, TEXTAREA MOUSE

EVENT CLASS ActionEvent

LISTENER INTERFACE ActionListener

METHODS actionPerformed() -> Button Pressing,Selecting item from list,events in textfield when enter is pressed mouseClicked() -> mouse click mouseEntered()-> mouse entered a component mouseExited()->mouse exited from component mouseDragged()->user dragged mouse mousePressed()-> mouse was pressed mouseReleased()-> mouse was released. mouseMoved() ->mouse move keyPressed()->when key

MouseEvent

MouseListener MouseMotionListener

KEYBOARD

KeyEvent

KeyListener

pressed keyReleased()->when key released keyTyped()-> when char is typed CHECKBOX,CHOICE WINDOWS ItemEvent WindowsEvent ItemListener WindowsListener itemStateChanged()-> when check box is checked off, item is selected from choice windowClosed() windowOpen() windowDeactivated() windowOpened

Handling ActionEvents An Action event is generated when a button is pressed, a list item is double clicked, or a menu item is selected. It is implemented using ActionListener interfaces Methods used in ActionEvent getActionCommand() -> it returns the name for the invoking ActionEvent object . eg: if a button is pressed the getActionCommand returns the label on the button getSource() -> returns the event object that generated the button. When Button is pressed, an action event is generated. This is sent to any listeners Inorder to receive the events, listeners object has to be registered with the event source by invoking addActionListener(this). Each listener implements an ActionListener interface. That interface defines the actionPerformed method, which is called when an event occurs.

Eg: Pgm which changes the background color when pressing a button import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="buttonevent" width=300 height=300> //</applet> public class buttonevent extends Applet implements ActionListener {

Button b1; public void init() { b1=new Button("Green"); add(b1); b1.addActionListener(this);// registering with source } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { setBackground(Color.green); } } } Eg:2 Pgm that displays the message that which button is being pressed import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="action" width=300 height=300> //</applet public class action extends Applet implements ActionListener { String msg=""; Label label=new Label("HELLO"); Button b1,b2,b3; public void init() { b1 = new Button("Yes"); b2 = new Button("No"); b3 = new Button("Cancel"); add(b1); add(b2); add(b3);

b1.addActionListener(this);

b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { msg="Clicked Yes Button"; } else if(ae.getSource()==b2) { label.setText("Clicked No Button"); } else { label.setText("Clicked Cancel Button"); } repaint(); } public void paint(Graphics g) { g.drawString(msg,6,100); } } Eg:3 Pgm that displays the message that which button is being pressed and changes the background color import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="action2" width=300 height=300> //</applet> public class action2 extends Applet implements ActionListener { String msg=""; Button b1,b2,b3; public void init() { b1=new Button("RED"); b2=new Button("GREEN"); b3=new Button("BLUE"); add(b1); add(b2);

add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent ae) { //String str=ae.getActionCommand(); if(ae.getSource()==b1) { msg="Clicked RED Button"; setBackground(Color.red); } else if(ae.getSource()==b2) { msg="Clicked" +b2.getLabel()+ " Button"; setBackground(Color.green); } else { msg="Clicked BLUE Button"; setBackground(Color.blue); } repaint(); } public void paint(Graphics g) { g.drawString(msg,6,100); } } Handling ItemEvent An ItemEvent is generated when a checkbox or a list item is clicked. It is implemented using ItemSelectable interfaces . Methods getItem() -> Used to obtain reference to the item that generated the event. getSelectedItem()-> used to obtain the item that is currently selected. getItemSelectable() -> used to obtain a reference to the itemselectable object that generated the event.

Eg : Pgm that changes the background colour display message that which checkbox has been checked off. import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="checkboxevent" width=300 height=300> //</applet> public class checkboxevent extends Applet implements ItemListener { String msg=""; Checkbox c1; public void init() { c1=new Checkbox("Green"); add(c1); c1.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { if(ie.getItemSelectable()==c1) { setBackground(Color.green); msg="you selected"+c1.getLabel(); } } public void paint(Graphics g) { g.drawString(msg,100,100); } } Eg: Program that displays the item selected in a choice import java.applet.*; import java.awt.event.*; //<applet code="choiceevent" width=300 height=300> //</applet> public class choiceevent extends Applet implements ItemListener { String msg=""; Choice c; public void init()

{ c=new Choice(); c.add("Mercury"); c.add("Venus"); c.add("Earth"); add(c); c.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { if(ie.getItemSelectable()==c) { msg="you selected "+c.getSelectedItem(); } repaint(); } public void paint(Graphics g) { g.drawString(msg,100,100); } } Eg:3 Program that displays the item checked off in a checkbox import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="radioevent" width=300 height=300> //</applet public class radioevent extends Applet implements ItemListener { TextField t1; CheckboxGroup cg; Checkbox c1,c2,c3; public void init() { cg=new CheckboxGroup(); c1 = new Checkbox("Windows xp",cg,false); c2 = new Checkbox("Windows 98",cg,false); c3 = new Checkbox("Windows 95",cg,false); t1=new TextField(25); add(c1); add(c2); add(c3);

add(t1); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { if(ie.getItemSelectable()==c1) { t1.setText(c1.getLabel()); showStatus(c1.getLabel()); t1.setBackground(Color.red); } else if(ie.getItemSelectable()==c2) { t1.setText(c2.getLabel()); showStatus(c2.getLabel()); t1.setBackground(Color.blue); } else { t1.setText(c3.getLabel()); showStatus(c3.getLabel()); t1.setBackground(Color.green); } } } Eg:4 import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="checkboxevent" width=300 height=300> //</applet public class checkboxevent extends Applet implements ItemListener { Checkbox c1,c2,c3; String msg; public void init() { c1 = new Checkbox("Windows xp"); c2 = new Checkbox("Windows 98"); c3 = new Checkbox("Windows 95"); add(c1);

add(c2); add(c3); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg="Current Status"; g.drawString(msg,6,80); msg="Windows XP:"+c1.getState(); g.drawString(msg,6,100); msg="Windows 98:"+c2.getState(); g.drawString(msg,6,120); msg="Windows 95:"+c3.getState(); g.drawString(msg,6,140); } } Handling Text Field Events are occurred in text field when user type any text in the text field and presses Enter Methods getText() -> returns the string currently contained in text field getSelectedText() -> returns the selected text. Eg Pgm to enter name & password in text field and to display the text as well as selected text import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="textevent" width=300 height=300> //</applet> public class textevent extends Applet implements ActionListener { String msg=""; Label l1,l2; TextField t1,t2;

public void init() { l1=new Label("NAME"); l2=new Label("PASSWORD"); t1=new TextField(20); t2=new TextField(20); t2.setEchoChar('*'); add(l1); add(t1); add(l2); add(t2); t1.addActionListener(this); t2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("Name is "+t1.getText(),10,80); g.drawString("Selected Text is "+t1.getSelectedText(),10,100); g.drawString("Password is "+t2.getText(),10,120); } } Handling Mouse Events To handle mouse events two interfaces has to be implemented, MouseListener and MouseMotionListener Methods used getX()-> returns the x coordinate of mouse getY() -> returns the y coordinate of mouse Eg: the following pgm displays the current coordinates of the mouse in the applets status window. Each time a button is pressed, the word Down is displayed.when the button is released the word Up is shown. If a button is clicked the message mouse clicked is displayed. As the mouse enters or exits the applet window it displays mouse entered and mouse exited. import java.awt.*;

import java.applet.*; import java.awt.event.*; //<applet code="mouseevent" width=300 height=300> //</applet> public class mouseevent extends Applet implements MouseListener,MouseMotionListener { String msg=""; int x=0,y=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { x=0; y=10; msg="Mouse Clicked"; repaint(); } public void mouseEntered(MouseEvent me) { x=0; y=10; msg="Mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { x=0; y=10; msg="mouse exited"; repaint(); } public void mousePressed(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Down"; repaint(); } public void mouseReleased(MouseEvent me)

{ x=me.getX(); y=me.getY(); msg="Up"; repaint(); } public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg="*"; showStatus("Dragging mouse at"+x+","+y); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("Moving mouse at"+me.getX()+","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,x,y); } } Handling Keyboard Events To handle Keyboard events KeyListener interface has to be implemented. getKeyChar() -> Returns the character that is pressed getKeyCode()-> Returns the key that is pressed. requestFocus() -> should be used in the program in order to process keyboard events. If it is not used then pgm will not receive any keyboard events. Eg: Pgm that handles keyboard presses import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="key" width=300 height=300> //</applet> public class key extends Applet implements KeyListener { String msg=""; public void init() { addKeyListener(this); }

public void keyPressed(KeyEvent ke) { showStatus("KEY DOWN"); } public void keyReleased(KeyEvent ke) { showStatus("KEY UP"); } public void keyTyped(KeyEvent ke) { msg +=ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg,10,10); } } Eg: import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="key" width=300 height=300> //</applet> public class key extends Applet implements KeyListener { String msg=""; public void init() { addKeyListener(this); requestFocus(); } public void keyPressed(KeyEvent ke) { showStatus("KEY DOWN"); } public void keyReleased(KeyEvent ke) { showStatus("KEY UP");

} public void keyTyped(KeyEvent ke) { msg +=ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg,10,10); } }

SWING

A Swing is an alternative to AWT . Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to familiar components such as buttons, check box and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees and tables Most Commonly Used Swing classes are Class ImageIcon JApplet JButton JCheckBox JComboBox JLabel JRadioButton JTabbedPane JTextField Description Encapsulates an icon The Swing version of Applet The Swing push button class The Swing checkbox class Encapsulates a combo box The Swing version of a label The swing version of a radio button Encapsulates a tabbed window The Swing version of text fiels

The Swing related classes are contained in javax.swing JApplet Fundamental to Swing is the JApplet class which extends Applet.. JApplet is rich in functionality that is not found in Applet. When adding component to an instance of JApplet we need to call add() method for the content pane of JApplet. The content pane is a container which holda all the swing components The content pane can be obtained by Container getContentPane() Eg: Container c=getContentPane() c.add() Icons and Labels In Swing icons are encapsulated by ImageIcon class, which creates an icon from image. Syntax ImageIcon(String filename)

ImageIcon class implements the icon interface that declares the methods Swing Labels are instances of the JLabel class. It can display text or an icon. Some of its constructors are JLabel(Icon i) JLabel(String s,Icon I,int align) eg: Pgm to create and display a label containing both an icon and a string. import java.awt.*; import javax.swing.*; //<applet code="jimage" width=300 height=300> //</applet> public class jimage extends JApplet { public void init() { Container c=getContentPane(); ImageIcon ii=new ImageIcon("india.jpg"); JLabel jl=new JLabel("INDIA", ii, JLabel.CENTER); c.add(jl); } } Text Fields JTextField which allows you to edit one line of text. Some of its constructors are shown here JTextField() JTextField(int cols) JTextField(String s) JTextField(String s, int cols) Eg: import java.awt.*; import javax.swing.*; //<applet code="jtextfield" width=300 height=300> //</applet> public class jtextfield extends JApplet { public void init() { Container c=getContentPane(); c.setLayout(new FlowLayout());

JTextField jf= new JTextField(15); c.add(jf); } } Buttons Swing buttons provide features that are not found in the Button class defined by the AWT. For example we can use an icon or image as a button. Some of its constructors are JButton(Icon i) JButton(String s) JButton(String s,Icon i) Here s and I are the string and icon used for the button Eg: The pgm displays two push buttons and a text field. Each button displays an icon that represents the flag of a country. When button is pressed the name of the button is displayed in the text field import java.awt.*; import javax.swing.*; import java.awt.event.*; //<applet code="jbuttonevent" width=300 height=600> //</applet> public class jbuttonevent extends JApplet implements ActionListener { JTextField jtf; public void init() { //Label l1=new Label("Do you want to continue"); Container c=getContentPane(); c.setLayout(new FlowLayout()); ImageIcon in=new ImageIcon("india.jpg"); JButton b1=new JButton(in); b1.setActionCommand("INDIA"); b1.addActionListener(this); c.add(b1); ImageIcon us=new ImageIcon("usa.jpg"); JButton b2=new JButton(us); b2.setActionCommand("USA"); b2.addActionListener(this); c.add(b2); jtf=new JTextField(25); c.add(jtf);

} public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand()); } }

Check Boxes The JCheckBox class which provides the functionality of a checkbox. Some of its constructors are JCheckBox(Icon i) JCheckBox(Icon i, Boolean state) JCheckBox(String s) JCheckBox(String s, Boolean state) JCheckBox(String s, Icon i, Boolean state) Here I is the icon for the button, s is text specified. If state is true the checkbox is initially selected otherwise it is not. When a check box is selected or deselected, an item event is generated. This is handled by itemStateChanged(). Inside itemStateChanged(), the getItem() method gets the JCheckBox object that generated the event. The getText() method gets the text for that check box Eg: The program displays three checkboxes and a text field. when a checkbox is selected its corresponding label is displayed on the text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; //<applet code="jcheckboxevent" width=300 height=300> //</applet public class jcheckboxevent extends JApplet implements ItemListener { String s; JCheckBox cb;

JTextField t; public void init() { Container c=getContentPane();

c.setLayout(new FlowLayout()); cb = new JCheckBox("Windows xp"); cb.addItemListener(this); c.add(cb); cb = new JCheckBox("Windows 98"); cb.addItemListener(this); c.add(cb); cb = new JCheckBox("Windows 95"); cb.addItemListener(this); c.add(cb); t=new JTextField(15); c.add(t); } public void itemStateChanged(ItemEvent ie) { JCheckBox cb=(JCheckBox)ie.getItem(); t.setText(cb.getText()); } } Radio Buttons Radio buttons are supported by the JRadioButton class. Radio button presses generate action events that are handled by actionPerformed( ) method. The getActionCommand( ) method gets the text that is associated with a radio button and uses it to set the text field.

import java.awt.*; import javax.swing.*; import java.awt.event.*; //<applet code="jradiobuttonevent" width=300 height=300> //</applet public class jradiobuttonevent extends JApplet implements ActionListener { JRadioButton c1,c2,c3; JTextField tf; public void init() { Container c=getContentPane(); c.setLayout(new FlowLayout()); c1 = new JRadioButton("Windows xp"); c2 = new JRadioButton("Windows 98"); c3 = new JRadioButton("Windows 95"); c1.addActionListener(this); c2.addActionListener(this); c3.addActionListener(this); tf=new JTextField(25); c.add(c1); c.add(c2); c.add(c3); c.add(tf); } public void actionPerformed(ActionEvent ae) { tf.setText(ae.getActionCommand()); } } Combo Boxes A Combo box is a combination of a text field and a drop down list through the JComboBox class. A combo box normally displays one entry. However it can also display a drop down list that allows a user to select different entry. JComboBoxs constructor is JComboBox() Eg: The program creates a combo box containing two items, India and Usa. When any one of the item is selected the corresponding flag is displayed. import java.awt.*;

import javax.swing.*; import java.awt.event.*; //<applet code="jcomboevent" width=600 height=600> //</applet> public class jcomboevent extends JApplet implements ItemListener { String msg=""; ImageIcon india,usa; JLabel jl; JComboBox jc; public void init() { Container c=getContentPane(); c.setLayout(new FlowLayout()); jc=new JComboBox(); jc.addItem("India"); jc.addItem("USA"); india=new ImageIcon("india.jpg"); usa=new ImageIcon("us.jpg"); jc.addItemListener(this); c.add(jc); jl=new JLabel(new ImageIcon("india.jpeg")); c.add(jl); } public void itemStateChanged(ItemEvent ie) { String s=(String)ie.getItem(); jl.setIcon(new ImageIcon(s+".jpg")); } } Tabbed Panes A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its content become visible. Only one of the folders may be selected at a time. Tabbed panes are encapsulated by the JTabbedPane class Eg: import java.awt.*; import javax.swing.*; //<applet code="jtabbedpane" width=300 height=300> //</applet> public class jtabbedpane extends JApplet {

public void init() { Container c=getContentPane(); //c.setLayout(new FlowLayout()); JTabbedPane jtp=new JTabbedPane(); jtp.addTab("Cities",new citiespanel()); jtp.addTab("Colors",new colorpanel()); jtp.addTab("Flavours",new flavourpanel()); c.add(jtp); } class citiespanel extends JPanel { public citiespanel() { JButton b1=new JButton("New York"); JButton b2=new JButton("London"); JButton b3=new JButton("Tokyo"); add(b1); add(b2); add(b3); } } class colorpanel extends JPanel { public colorpanel() { JCheckBox cb1=new JCheckBox("Red"); JCheckBox cb2=new JCheckBox("Green"); JCheckBox cb3=new JCheckBox("Blue"); add(cb1); add(cb2); add(cb3); } } class flavourpanel extends JPanel { public flavourpanel() { JComboBox com=new JComboBox(); com.addItem("Vanilla"); com.addItem("Chocolate"); com.addItem("strawberry"); add(com); }

} } Scroll Panes A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its constructors are shown here: JScrollPane(Component comp) JScrollPane(int vsb, int hsb) JScrollPane(Component comp, int vsb, int hsb) Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the ScrollPaneConstants interface. Some examples of these constants are described as follows: Constant HORIZONTAL_SCROLLBAR_ALWAYS scroll bar HORIZONTAL_SCROLLBAR_AS_NEEDED bar,if needed VERTICAL_SCROLLBAR_ALWAYS bar VERTICAL_SCROLLBAR_AS_NEEDED needed Steps to follow to use a scroll pane in an applet: 1. Create a JComponent object. 2. Create a JScrollPane object. (The arguments to the constructor specify the component and the policies for vertical and horizontal scroll bars.) 3. Add the scroll pane to the content pane of the applet. SOFTWARE eg:AVA import java.awt.*; import javax.swing.*; //<applet code="jscrollpane" width=300 height=250> //</applet> Description Always provide horizontal Provide horizontal scroll Always provide vertical scroll Provide vertical scroll bar, if

public class jscrollpane extends JApplet { public void init() { Container c = getContentPane(); c.setLayout(new BorderLayout()); ImageIcon ii=new ImageIcon("flower.jpg"); JLabel l=new JLabel(ii); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(l, v, h); c.add(jsp, BorderLayout.CENTER); }} Tables A table is a component that displays rows and columns of data. we can drag the cursor on column boundaries to resize columns. Tables are implemented by the JTable class, which extends JComponent. One of its constructors is JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings. Steps for using a table in an applet: 1. Create a JTable object. 2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.) 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane of the applet. import java.awt.*; import javax.swing.*; //<applet code="jtable" width=400 height=200> //</applet> public class jtable extends JApplet { public void init() { Container c = getContentPane();

c.setLayout(new BorderLayout()); // Initialize column headings final String[] colHeads = { "Name", "Phone", "Fax" }; // Initialize data final Object[][] data = { { "Gail", "4567", "8675" }, { "Ken", "7566", "5555" }, { "Viviane", "5634", "5887" }, { "Melanie", "7345", "9222" }, { "Anne", "1237", "3333" }, { "John", "5656", "3144" }, { "Matt", "5672", "2176" }, { "Claire", "6741", "4244" }, { "Erwin", "9023", "5159" }, { "Ellen", "1134", "5332" }, { "Jennifer", "5689", "1212" }, { "Ed", "9030", "1313" }, { "Helen", "6751", "1415" } }; // Create the table JTable table = new JTable(data, colHeads); // Add table to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); // Add scroll pane to the content pane c.add(jsp, BorderLayout.CENTER); } }

Frame A top-level display surface (a window) with a border and title. An instance of the Frame class may has a title bar, menu bar and resizable border. A frame can be created by the statement JFrame f=new JFrame(Frame Window) After the window is created, it must be displayed by calling setVisible( ) The window can be sized by calling resize() Eg: f.setSize(300,300);// to set the frame size f.setVisible(true); // to display frame

when the window is closed, the application should stop. So we should include the statement: f.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE); The JFrame.EXIT_ON_CLOSE constant sets the Java application to terminate when the window is closed. Eg: Pgm that shows a sample frame window import java.awt.*; import javax.swing.*; class fr extends JFrame { static JFrame f; public static void main(String[] args) { f=new JFrame("HELLO"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setSize(300,350); f.setVisible(true); } } Adding swing components to Frame Eg: import java.awt.*; import javax.swing.*; import java.awt.event.*; public class framebutton extends JApplet implements ActionListener { static JFrame f; JTextField jtf; public framebutton() { Container c=getContentPane(); c.setLayout(new FlowLayout()); ImageIcon in=new ImageIcon("india.jpg"); JButton b1=new JButton(in); b1.setActionCommand("INDIA"); b1.addActionListener(this); c.add(b1); ImageIcon us=new ImageIcon("usa.jpg"); JButton b2=new JButton(us); b2.setActionCommand("USA"); b2.addActionListener(this); c.add(b2); jtf=new JTextField(25); c.add(jtf); } public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand()); } public static void main(String args[]) { f=new JFrame("Hello"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); framebutton obj= new framebutton(); f.add(obj); f.setSize(600,600); f.setVisible(true); }

Você também pode gostar