Since multiple threads run independently without any communication between them, some problems may arise because of this asynchronous behavior of threads. Sometimes, we need an operation to be performed by only one thread at a time. Performing the same task by two threads simultaneously may lead to inconsistent results. So to ensure that two thread don’t execute the conflicting operations together and to initiate communication among thread, a process called synchronization is used. [Read more…] about Synchronization in Java Example
Thread Priorities Example in Java
Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. Higher priority threads get more CPU time than lower priority threads. A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower priority thread. [Read more…] about Thread Priorities Example in Java
Four Threads in Java Example
isAlive() and Join() Example in Java By Inheriting Thread Class
isAlive() and Join() Example in Java By Implementing Runnable Interface
isAlive() Example in Java
To determine whether a thread has finished. we can call isAlive() on the thread. This method is defined by Thread and its syntax is :
final boolean isAlive()
This method returns true if the thread upon which it is called is still running otherwise it returns false.
Two Threads in Java by Implementing Runnable Interface
Multiple Threads in Java by Inheritance
Multiple Threads in Java by Implementing Runnable Interface
Multiple Threads in Java Example
We first make a class MultipleThreads which extends Thread class and then we create an instance of that class t1 and pass the string “Child Thread” as parameter to it which assigns the name of the thread as Child Thread and also displays the information of the child thread on the screen. After that the start() method is invoked on that object which initiates the run() method. Before executing run() method of MultipleThreads, control returns to main(). In main() method, the for loop is executed which is supposed to print Mainthread : 1 [Read more…] about Multiple Threads in Java Example
Implementing Runnable Interface in Java Example
Another method to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. We can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run(). [Read more…] about Implementing Runnable Interface in Java Example
Extending Thread Class in Java Example
One way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread. [Read more…] about Extending Thread Class in Java Example
currentThread() in Java Example
In this Java Example, a reference to the current thread (the main thread) is obtained by calling currentThread(), and this reference is stored in a local variable t. Then, we display the information about the thread. After that, a loop counts from 0 to 10, pausing one second between each line. The pause is accomplished by the sleep() method. The argument to sleep() specifies the delay period in milliseconds. The sleep() method might throw an InterruptedException if some other thread interrupts the sleeping one. [Read more…] about currentThread() in Java Example
MenuBar class in Java Example
The MenuBar class encapsulates the platform’s concept of a menu bar bound to a frame. In order to associate the menu bar with a Frame object, call the frame’s setMenuBar method.
A menu bar handles keyboard shortcuts for menu items, passing them along to its child menus. Keyboard shortcuts provide the user with an alternative to the mouse for invoking a menu item and the action that is associated with it. Each menu item can maintain an instance of MenuShortcut.
Menu Interface
Method | Returns | Notes |
MenuBar() | Adds these to Frames only | |
add(Menu m) | Menu | Add a menu object |
countMenus() | Int> | How many menu objects currently? |
getHelpMenu() | Menu> | Returns null if setHelpMenu() hasn’t been called |
getMenu(int i) | Menu> | Get the menu object |
remove(int index) | Void> | Remove a menu at the index |
remove(MenuComponent m) | Void> | Remove a particular menu object |
setHelpMenu(Menu m) | Void> | Designate a particular menu as the Help menu |
Menu(String label) |
| If tearOff is true, some platforms allow tear-off menus |
Menu(String label, boolean tearoff) |
|
|
add(MenuItem mi) | MenuItem | Add a entry in a menu |
add(String label) | Void | Implicitly create a menu item with this label |
countItems() | Int> | How many items in this menu? |
addSeparator() | Void> | Just a little white space |
getItem(int i) | MenuItem> | Return the i th item |
remove(int index) | Void> | Remove the item at the index |
remove(MenuComponent item) | Void> | Remove a particular item |
Menultem Interface
Method | Returns | Notes |
MenuItem(String label) |
| A single totally plain menu item |
disable() | Void | Disable and usually lowlight the menu item |
enable() enable(boolean cond) | Void | Enable and restore the visual state of the item |
getLabel() | String | Get the text currently on the menu item |
isEnabled() | boolean | Is this item currently enabled? |
setLabel(String label) | Void | Put a new text label on the item |
MenuComponent Interface
Method | Returns | Notes |
getFont() | Font | Not often used |
getParent() | MenuContainer | May need to be used with a cast |
setFont(Font f) | Void | Not often used |
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="MenuBarClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class MenuBarClass extends Frame
{
MenuBar mb=new MenuBar();
Label label=new Label(" ");
public static void main(String args[])
{
demomenu1 app=new demomenu1();
}
public demomenu1()
{
super("Demonstration of Menus");
Panel panel=new Panel();
panel.add(label);
add("Center",panel);
addWindowListener(new WindowEventHandler());
menudetails();
setMenuBar(mb);
pack();
setSize(400,400);
show();
}
void menudetails()
{
Menu fmenu=new Menu("File");
Menu emenu=new Menu("Edit");
Menu hmenu=new Menu("Help");
MenuItem newfitem=new MenuItem("New");
MenuItem exitfitem=new MenuItem("Exit");
fmenu.add(newfitem);
fmenu.addSeparator();
fmenu.add(exitfitem);
MenuItem cuteitem=new MenuItem("Cut");
MenuItem copyitem=new MenuItem("Copy");
MenuItem pasteitem=new MenuItem("Paste");
CheckboxMenuItem refreshitem=new CheckboxMenuItem("Refresh",true);
emenu.add(cuteitem);
emenu.add(copyitem);
emenu.add(pasteitem);
emenu.addSeparator();
emenu.add(refreshitem);
Menu sendmenu=new Menu("Send To");
MenuItem drivesitem=new MenuItem("Send to Drive");
MenuItem deskitem=new MenuItem("send to Desktop");
sendmenu.add(drivesitem);
sendmenu.add(deskitem);
emenu.add(sendmenu);
MenuItem abouthitem=new MenuItem("About");
hmenu.add(abouthitem);
mb.add(fmenu);
mb.add(emenu);
mb.add(hmenu);
Menuhandler mh=new Menuhandler();
newfitem.addActionListener(mh);
exitfitem.addActionListener(mh);
cuteitem.addActionListener(mh);
copyitem.addActionListener(mh);
pasteitem.addActionListener(mh);
refreshitem.addActionListener(mh);
drivesitem.addActionListener(mh);
deskitem.addActionListener(mh);
abouthitem.addActionListener(mh);
}
class Menuhandler implements ActionListener,ItemListener
{
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
label.setText(s);
validate();
if(s.equals("Exit")) System.exit(0);
}
public void itemStateChanged(ItemEvent e)
{
CheckboxMenuItem
item=(CheckboxMenuItem)e.getItemSelectable();
String status;
if(item.getState())status="You checked:";
else status="you unchecked";
status+=item.getLabel();
label.setText(status);
validate();
}
}
class WindowEventHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
ShapeChooser in Java Example
FontMetrics Class in Java Example
The FontMetrics class is used to return the specific parameters for a particular Font object. An object of this class is created using the getFontMetrics() methods supported by the Component class and other classes, such as the Graphics and Toolkit classes. The FontMetrics access methods provide access to the details of the implementation of a Font object.
The bytesWidth(), charWidth(), charsWidth(), getWidth(), and stringWidth() methods are used to determine the width of a text object in pixels. These methods are essential for determining the horizontal position of text on the screen.
FontMetrics Useful Interface
Method | Returns | Notes |
bytesWidth(bytedatea[], int offset, int length) | Int | Returns the width (in pixels) of the bytes from offset for length |
charsWidth(bytedatea[], int offset, int length) | Int | Returns the width (in pixels) of the characters from offset for length |
charWidth(char c) | Int | How wide is this one character? |
charWidth(char c) | Int | How wide is this one character? |
getAscent() | Int | How much does a standard character rise above the baseline of the font? |
getDescent() | Int | How much does a standard character fall below the baseline of the font? |
getFont() | Font | What is the current font? |
getHeight() | Int | What is the standard height of this font? |
getLeading() | Int | What is the standard spacing between lines of this font? |
getMaxAdvance() | Int | What is the largest gap between characters? |
getMaxAscent() | Int | What is the largest rise above the baseline for this font? |
getMaxDescent() | Int | What is the largest fall below the baseline for this font? |
getWidths() | Int[] | Returns a 256 cell array of the advance widths for the first 256 characters in this font |
stringWidth(String str) | Int | This is how wide the string would be on screen (in pixels) |
import java.awt.*;
/* <APPLET CODE ="FontMetricsClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontMetricsClass extends java.applet.Applet
{
public void paint(Graphics g)
{
String s="Hello Java";
Font f=new Font("Arial",Font.BOLD+Font.ITALIC,20);
g.setFont(f);
FontMetrics met=g.getFontMetrics(f);
int ascent=met.getAscent();
int height=met.getHeight();
int leading=met.getLeading();
int baseline=leading+ascent;
for(int i=0;i<10;i++)
{
g.drawString("Line"+String.valueOf(i),10,baseline);
baseline+=height;
}
}
}
Font Class in Java Example
The Font class provides a method of specifying and using fonts. The Font class constructor constructs font objects using the font’s name, style (PLAIN, BOLD, ITALIC, or BOLD + ITALIC), and point size. Java’s fonts are named in a platform independent manner and then mapped to local fonts that are supported by the operating system on which it executes. The getName() method returns the logical Java font name of a particular font and the getFamily() method returns the operating system-specific name of the font. The standard Java font names are Courier, Helvetica, TimesRoman etc.
The font can be set for a graphics context and for a component.
Font getFont() It is a method of Graphics class used to get the font property
setFont(Font f) is used to set a font in the graphics context
There are following logical font names which are standard on all platforms and are mapped to actual fonts on a particular platform:
“Serif” variable pitch font with serifs
“SansSerif” variable pitch font without serifs
“Monospaced” fixed pitch font
“Dialog” font for dialogs
“DialogInput” font for dialog input
“Symbol” mapped to the Symbol font
Font style is specified using constants from the Font class:
Font.BOLD
Font.ITALIC
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="FontClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends java.applet.Applet
{
Font f;
String m;
public void init()
{
f=new Font("Arial",Font.ITALIC,20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
g.setColor(c);
g.drawString(m,4,20);
}
}
Color Class in Java Examples
The Color class is used to create colors in the default RGB color space or colors in any color spaces defined by a ColorSpace. Every color has an implicit alpha value of 1.0 or an explicit one provided in the constructor. The alpha value defines the transparency of a color and can be represented by a float value in the range 0.0 – 1.0 or 0 – 255. An alpha value of 1.0 or 255 means that the color is completely opaque and an alpha value of 0 or 0.0 means that the color is completely transparent. When constructing a Color with an explicit alpha or getting the color/alpha components of a Color, the color components are never pre multiplied by the alpha component.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <APPLET CODE ="ColorClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class ColorClass extends Applet implements ItemListener
{
Choice l;
public void init()
{
l=new Choice();
l.addItem("Black");
l.addItem("Blue");
l.addItem("Cyan");
l.addItem("Dark Gray");
l.addItem("Gray");
l.addItem("Green");
l.addItem("Light Gray");
l.addItem("Magenta");
l.addItem("Orange");
l.addItem("Pink");
l.addItem("Red");
l.addItem("White");
l.addItem("Yellow");
add(l);
l.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
if(l.getSelectedItem()=="Black")
{
setBackground(Color.black);
}
if(l.getSelectedItem()=="Blue")
{
setBackground(Color.blue);
}
if(l.getSelectedItem()=="Cyan")
{
setBackground(Color.cyan);
}
if(l.getSelectedItem()=="Dark Gray")
{
setBackground(Color.darkGray);
}
if(l.getSelectedItem()=="Gray")
{
setBackground(Color.gray);
}
if(l.getSelectedItem()=="Green")
{
setBackground(Color.green);
}
if(l.getSelectedItem()=="Light Gray")
{
setBackground(Color.lightGray);
}
if(l.getSelectedItem()=="Magenta")
{
setBackground(Color.magenta);
}
if(l.getSelectedItem()=="Orange")
{
setBackground(Color.orange);
}
if(l.getSelectedItem()=="Red")
{
setBackground(Color.red);
}
if(l.getSelectedItem()=="Pink")
{
setBackground(Color.pink);
}
if(l.getSelectedItem()=="White")
{
setBackground(Color.white); }
if(l.getSelectedItem()=="Yellow")
{
setBackground(Color.yellow);
}
}
}
Keyboard Events in Java Applet
Keyboard Events in Java Example
It is a subclass of the abstract InputEvent class and is generated when the user presses or releases a key or does both i.e. types a character.
When a key is pressed, the event generated is KEY_PRESSED
When a key is released, the event generated is KEY_RELEASED
When a character is typed on the keyboard, that is a key is pressed and then released, the event generated is KEY_TYPED
Following are the types of methods provided by KeyEvent class
int getKeyCode() It is used for getting the integer code associated with a key. It is used for KEY_PRESSED and KEY_RELEASED events. The keycodes are defined as constants in KeyEvent class
char getKeyChar() This method is used to get the Unicode character of the key pressed. It works with the KEY_TYPED events
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="KeyboardEvents.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class KeyboardEvents extends Applet implements KeyListener
{
TextArea tpress,trel;
TextField t;
public void init()
{
t=new TextField(20);
t.addKeyListener(this);
tpress=new TextArea(3,70);
tpress.setEditable(false);
trel=new TextArea(3,70);
trel.setEditable(false);
add(t);
add(tpress);
add(trel);
}
public void keyTyped(KeyEvent e)
{
disppress(e,"Key Typed:");
}
public void keyPressed(KeyEvent e)
{
disppress(e,"KeyPressed:");
}
public void keyReleased(KeyEvent e)
{
String charString,keyCodeString,modString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
charString="Key character='"+c+"'";
keyCodeString="key code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
modString="modifiers="+modifiers;
trel.setText("Key released"+charString+keyCodeString+modString);
}
protected void disppress(KeyEvent e,String s)
{
String charString,keyCodeString,modString,tmpString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
if(Character.isISOControl(c))
{
charString="key character=(an unprintable control character)";
}
else
{
charString="key character='"+c+"'";
}
modString="modifiers="+modifiers;
tmpString=KeyEvent.getKeyModifiersText(modifiers);
if(tmpString.length()>0)
{
modString+="("+tmpString+")";
}
else
{
modString+="(no modifiers)";
}
keyCodeString="key code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
tpress.setText(s+charString+keyCodeString+modString);
}
}
MouseMotionListener Example in Java
The addMouseMotionListener () method to handle events related to mouse movements. methods mouseDragged () and mouseMoved () receive events. Any of the objects of the Canvas, JDialog, JFrame, JPanel and JWindow classes can produce such events. To mark an object can listen to these events must implement the interface MouseMotionListener, and we have added the producer of events by the method:
public void addMouseMotionListener(MouseMotionListener mml)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="MouseMotionListenerExample.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class MouseMotionListenerExample extends Applet implements MouseListener,MouseMotionListener
{
TextField t;
public void init()
{
t=new TextField(100);
add(t);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e)
{
t.setText("Mouse Pressed; # of clicks: "+e.getClickCount()+"at position "+e.getX()+","+e.getY());
}
public void mouseReleased(MouseEvent e)
{
t.setText("Mouse released; #of clicks: " +e.getClickCount());
}
public void mouseEntered(MouseEvent e)
{
t.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
t.setText("Mouse Exited");
}
public void mouseClicked(MouseEvent e)
{
t.setText("Mouse clicked(# of clicks:"+e.getClickCount());
}
public void mouseMoved(MouseEvent e)
{
t.setText("Mouse is moved to Location"+e.getX()+","+e.getY());
}
public void mouseDragged(MouseEvent e)
{
t.setText("Mouse is dragged to Location:"+e.getX()+","+e.getY());
}
}
MouseListener in Java Awt Example
The MouseEvent event is used by two different interfaces:
java.awt.event.MouseListener and java.awt.event.MouseMotionListener. The first interface is designed to process events button press and mouse detection entrance and exit of a mouse over a component. The second is the processing the mouse movement.
The java.awt.event.MouseListener interface requires the implementation of severalmethods : mousePressed, mouseReleased, mouseEntered, and mouseExitedmouseClicked. To reduce the amount of required code can opt for the extension of the class java.awt.event.MouseAdapter that provides a null implementation of the above methods.
The java.awt.event.MouseMotionListener interface requires the implementation of following methods : mouseDragged and mouseMoved . As for the interface MouseListener, can opt for the extension of the class to MouseMotionAdapter reducing the amount of code required . The MouseEvent event has the following specific methods :
Method | Description |
getClickCount () | Returns the number of clicks associated with this event. |
GetPoint () | Returns a Point object containing the coordinates of where the activation of the mouse occurred. |
getX () | Returns the x coordinate of where they occurred Pressing the mouse. |
getY () | Returns the y coordinate of where they occurred Pressing the mouse.
|
isPopupTrigger () | Checks if this event is associated with display Popup menus on this platform.
|
TranslatePoint (int, int) | Translates the coordinate of the event with the values specified. |
Textarea Example in Java Awt
This component, known as multiline input box or memo, allows creation of an area for entering and editing text containing multiple lines in order to can even contain more text than can be displayed. Belongs to the class java.awt.TextArea and java.awt.TextField as the component shares the characteristics of their ancestral component java.awt.TextComponent.
The TextArea component can be adjusted to allow or not to issue and display scroll bars to help control the text display. The class java.awt.TextArea contain, among others, the following constructors and methods:
Method | Description |
TextArea ( ) | Constructs a component with both without text scrollbars . |
TextArea ( int , int ) | Constructs a component capable of displaying text without the number of rows and columns of text specified with the two scroll bars . |
TextArea ( String ) | Constructs a component containing the text specified with the two scroll bars . |
TextArea (String , int , int ) | Constructs a component with text data can display the number of rows and columns of text specified with the two scroll bars. |
TextArea (String ,int,int,int ) | Constructs a component with text data can display the number of rows and columns of text specified and also the scrollbars indicated. |
append ( String ) | Appends the given text to the end of the text contained by component. |
getColumns ( ) | Gets the number of columns of text . |
getRows ( ) | Gets the number of lines of text . |
insert ( String , int ) | Inserts the given text at the position indicated . |
replaceRange ( String , int , int ) | Replace the existing text between positions indicated by the given text . |
SetColumns ( int ) | Specifies the number of text columns . |
SetRows ( int ) | Specifies the number of lines of text . |
The display of scrollbars can not be modified after the construction of component. Its specification uses a constructor that accepts as a parameter the constant TextArea.SCROLLBARS_BOTH, TextArea.SCROLLBARS_NONE,TextArea.SCROLLBARS_VERTICAL_ONLY,TextArea.SCROLLBARS_HORIZONTAL_ONLY.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <APPLET CODE ="TextareaExampleAwt.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class TextareaExampleAwt extends Applet implements ActionListener
{
String t;
Button b1,b2;
TextArea txt;
public void init()
{
txt=new TextArea("Welcome to Java",2,30);
b1=new Button("Upper Case");
b2=new Button("Lower Case");
add(txt);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
String k=event.getActionCommand();
if(k.equals("Upper Case"));
{
t=txt.getText();
t=t.toUpperCase();
txt.setText(t);
}
if(k.equals("Lower case"))
{
t=txt.getText();
t=t.toLowerCase();
txt.setText(t);
}
}
}
Textarea in Java Applet Example
While single-line input is handled by TextField, many applications need to display and/ or edit larger bocks of text. TextArea is the AWT component that supports this feature. TextArea class provides a rectangular area (in rows and columns) for user interaction.
Editing within a TextArea is basically the same as editing within a TextField. When typing in the text area, the user can perform most of the native cut, copy, and paste operations. However, the AWT doesn’t provide specific events for these.
TextArea Useful Interface
Method | Returns | Notes |
TextArea() |
| Rows and columns are approximate, some windowing systems don’t seem “perfect” |
TextArea(int rows, int cols) |
| |
TextArea(String text) |
|
|
TextArea(String text, int rows, int cols) |
|
|
appendText(String str) | Void | Take the string on the end of the area |
getColumns() | Int | How wide is the text area |
getRows() | Int | How tall the text area |
insertText(String str, int pos) | Void | Insert the string in the existing text at the index passed in; note that this doesn’t use rows and columns |
minimumSize() | Dimension |
|
minimumSize(int rows, int cols) | Dimension |
|
preferredSize() | Dimension |
|
preferredSize(int rows, int cols) | Dimension |
|
replaceText(String str, int start, int end) | Void | Same as TextField.setText() |
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <APPLET CODE ="TextareaJavaApplet.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class TextareaJavaApplet extends Applet implements ActionListener
{
TextArea txt;
Button b1,b2;
String s1,s2;
Label l1,l2,l3;
TextField t1,t2,t3;
public void init()
{
txt = new TextArea(5,30);
add(txt);
s1="This is the text which is already present in textarea\nMerry"+ "Christmas to
you\nToday it may rain";
txt.append(s1);
s2="In the middle this text will be inserted";
b1=new Button("insert Text");
add(b1);
b1.addActionListener(this);
l1=new Label("Replacing a range of above text with new text.Enter starting location");
add(l1);
t1=new TextField(10);
add(t1);
l2=new Label("Ending range");
add(l2);
t2=new TextField(10);
add(t2);
l3=new Label("Replacing with");
add(l3);
t3=new TextField(10);
add(t3);
b2=new Button("Replace");
add(b2);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int start,end;
if(e.getSource()==b1)
{
txt.insert(s2,12);
}
if(e.getSource()==b2)
{
start=Integer.parseInt(t1.getText());
end=Integer.parseInt(t2.getText());
txt.replaceRange(t3.getText(),start,end);
}
}
}
Choice and list Control in Java Applet Example
The java.awt.Choice component implements a list of items where only the selected item is displayed. The list appears as a drop down (pop-down menu) menu can be seen through the touch of a button built into the component, so it is also known as a check box or combobox. In the same manner as in component java.awt.List a vertical scrollbar is automatically displayed when the list can not simultaneously show all the items they contain. The selection only operate in simple mode, that is, only one item can be selected at a time, and the choice of an item not selected selects and vice versa.
This component generates only type events ItemEvent, thus requiring the implement the ItemListener interface for processing. Table contains the constructors and methods available in the main class java.awt.Choice:
Method | Description |
Choice () | Constructs a checkbox. |
add (String) | Adds the specified text as a new item the end of the list.
|
addItemListener (ItemEvent) | Registers a listener class (processor events) ItemListener for the component. |
getItem (int) | Gets the indicated item. |
GetItemCount () | Gets the number of items in the list. |
getSelectedIndex () | Gets the position of the selected item. |
GetSelectedItem () | Gets the selected item. |
insert (String, int) | Inserts the given item at the specified position. |
remove (int) | Removes the specified item from the list. |
removeAll () | Removes all items from the list. |
select (INT) | Selects the item displayed in the list. |
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/* <APPLET CODE ="ChoiceListControl.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class ChoiceListControl extends Applet implements ItemListener
{
List ls;
Choice choice;
Label lb1,lb2,lb3;
TextField t;
Button b1;
public void init()
{
setLayout(new BorderLayout());
Panel p1= new Panel();
Panel p2= new Panel();
p1.setLayout(new GridLayout(2,2));
p2.setLayout(new GridLayout(1,1));
lb1=new Label("Select an Option");
p1.add(lb1);
choice =new Choice();
choice.addItem("Snacks");
choice.addItem("Drinks");
choice.addItemListener(this);
p1.add(choice);
lb2=new Label("What you want to have");
p1.add(lb2);
ls=new List(4,true);
p1.add(ls);
ls.add("Pastry...8");
ls.add("French Fries...20");
ls.add("Burger...15");
ls.add("Dosa...20");
ls.addItemListener(this);
lb3=new Label("Your Bill is");
p2.add(lb3);
t=new TextField(20);
p2.add(t);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
}
public void itemStateChanged(ItemEvent e)
{
int amt,i;
String st[]= new String[4];
amt=0;
if(e.getSource()==choice)
{
if(choice.getSelectedItem()=="Snacks")
{
ls.removeAll();
ls.add("Pastry...8");
ls.add("French Fries...20");
ls.add("Burger...15");
ls.add("Dosa...20");
}
else
{
ls.removeAll();
ls.add("Coffee...12");
ls.add("Cola...12");
ls.add("Tea...5");
ls.add("Juice...15");
}
}
else
{
st=ls.getSelectedItems();
for(i=0;i<st.length;i++)
{
if(st[i].equals("Pastry..8"));
{
amt=amt+8;
}
if(st[i].equals("French Fries..20"));
{
amt=amt+20;
}
if(st[i].equals("Burger..15"));
{
amt=amt+15;
}
if(st[i].equals("Dosa..20"));
{
amt=amt+20;
}
if(st[i].equals("Coffee..12"));
{
amt=amt+12;
}
if(st[i].equals("Cola..12"));
{
amt=amt+12;
}
if(st[i].equals("Tea..5"));
{
amt=amt+5;
}
if(st[i].equals("Juice..15"));
{
amt=amt+15;
}
} t.setText(String.valueOf(amt));
}
}
}
Checkbox Group in Java Applet Example Using Panel and layout
Checkbox is used to indicate whether a thing is on or off, it’s very common to use a group of them to indicate which one of many choices is active. This is the exact functional equivalent of a Choice object with static contents. In the AWT, a group of checkboxes used for a one-of-many control is called a CheckboxGroup. Many systems call this kind of control a radio button or other similar name.
When the user clicks on one of the checkboxes in the group, the generated event can be processed in any of the objects containing the Checkbox.
CheckboxGroup Useful Interface
Method | Returns | Notes |
CheckboxGroup() | Creates an empty group | |
getCurrent() | Checkbox | Returns the currently ON box |
setCurrent(Checkbox box) | Void | Make the passed Checkbox the ON box |
[Read more…] about Checkbox Group in Java Applet Example Using Panel and layout