Back to: Java Tutorials For Beginners and Professionals
AWT Controls in Java with Examples
In this article, I am going to discuss AWT Controls in Java with Examples. Please read our previous article, where we discussed Abstract Windows Toolkit (AWT) in Java. At the end of this article, you will understand the following pointers in detail which are related to AWT Controls in java with Examples.
- AWT Controls in Java
- Labels
- Buttons
- Canvas
- Checkbox
- Radio Buttons
- AWT Choice Control in Java
- List Control
- AWT Scroll Bar Control in java
- AWT TextComponent Controls in Java
AWT Controls in Java:
Controls are components that allow a user to interact with your application in various ways. The AWT supports the following types of controls:
Labels
The easiest control to use is a label. A label contains a string and is an object of type Label. Labels are passive controls that do not support any interaction with the user.
Creating Label : Label l = new Label(String);
Label Constructors:
- Label() throws HeadlessException: It creates a blank label.
- Label(String str) throws HeadlessException: It creates a label that contains the string specified by str.
- Label(String str, int how): It creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, Label.CENTER.
Label Methods:
- void setText(String str): It is used to set or change the text in a label by using the setText() method. Here, str specifies the new label.
- String getText(): It is used to obtain the current label by calling getText() method. Here, the current label is returned.
- void setAlignment(int how): It is used to set the alignment of the string within the label by calling setAlignment() method. Here, how is one of the alignment constants?
- int getAlignment(): It is used to obtain the current alignment, getAlignment() is called.
Example to understand AWT Label Control in Java:
import java.awt.*; import java.applet.*; /* <applet code = "LabelDemo" width=300 height=200> </applet> */ public class LabelDemo extends Applet { public void init () { Label one = new Label ("One"); Label two = new Label ("Two"); Label three = new Label ("Three"); add (one); add (two); add (three); } }
Output:
AWT Button Control in Java
The most widely used control is Button. A button is a component that contains a label and that generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
Button Constructors:
- Button() throws HeadlessException: It creates an empty button.
- Button(String str) throws HeadlessException: It creates a button that contains str as a label.
Button Methods :
- void setLabel(String str): You can set its label by calling setLabel(). Here, str is the new Label for the button.
- String getLabel(): You can retrieve its label by calling getLabel() method.
Example to understand AWT Button Control in Java:
import java.awt.*; import java.awt.event.*; public class ButtonDemo extends Frame { Button b1, b2; ButtonDemo () { b1 = new Button ("OK"); b2 = new Button ("CANCEL"); this.setLayout (null); b1.setBounds (100, 100, 80, 40);; b2.setBounds (200, 100, 80, 40); this.add (b1); this.add (b2); this.setVisible (true); this.setSize (300, 300); this.setTitle ("button"); this.addWindowListener (new WindowAdapter () { public void windowClosing (WindowEvent we) { System.exit (0); } }); } public static void main (String args[]) { new ButtonDemo (); } }
Output:
AWR Canvas Control in java
Canvas encapsulates a blank window upon which you can draw in an application or receive inputs created by the user.
Canvas Constructor:
- Canvas() : Constructs a new Canvas.
- Canvas (GraphicsConfiguration config) : Constructs a new Canvas given a GraphicsConfiguration object.
Canvas Methods:
- void addNotify(): It is used to create the peer of the canvas.
- void createBufferStrategy(int numBuffers): It is used to create a new strategy for multi-buffering on this component.
- BufferStrategy getBufferStrategy(): It is used to return the BufferStrategy used by this component.
Example to understand AWT Canvas Control in Java:
import java.awt.*; import java.awt.event.*; public class CanvasDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public CanvasDemo () { prepareGUI (); } public static void main (String[]args) { CanvasDemo awtControlDemo = new CanvasDemo (); awtControlDemo.showCanvasDemo (); } private void prepareGUI () { mainFrame = new Frame ("Java AWT Examples"); mainFrame.setSize (400, 400); mainFrame.setLayout (new GridLayout (3, 1)); mainFrame.addWindowListener (new WindowAdapter () { public void windowClosing (WindowEvent windowEvent) { System.exit (0); } }); headerLabel = new Label (); headerLabel.setAlignment (Label.CENTER); statusLabel = new Label (); statusLabel.setAlignment (Label.CENTER); statusLabel.setSize (350, 100); controlPanel = new Panel (); controlPanel.setLayout (new FlowLayout ()); mainFrame.add (headerLabel); mainFrame.add (controlPanel); mainFrame.add (statusLabel); mainFrame.setVisible (true); } private void showCanvasDemo () { headerLabel.setText ("Control in action: Canvas"); controlPanel.add (new MyCanvas ()); mainFrame.setVisible (true); } class MyCanvas extends Canvas { public MyCanvas () { setBackground (Color.GRAY); setSize (300, 300); } public void paint (Graphics g) { Graphics2D g2; g2 = (Graphics2D) g; g2.drawString ("It is a custom canvas area", 70, 70); } } }
Output:
AWT Checkbox Control in java
A checkbox may be a control that’s used to turn an option on or off. It consists of a little box that will either contain a check or not. There’s a label related to each checkbox that describes what option the box represents. You modify the state of a checkbox by clicking on. Checkboxes are often used individually or as a part of a gaggle. Checkboxes are objects of the Checkbox class.
Creating Checkbox : Checkbox cb = new Checkbox(Label);
Checkbox Constructor
- Checkbox() throws HeadlessException: Creates a checkbox whose label is initially blank. The state of the checkbox is unchecked.
- Checkbox(String str) throws HeadlessException: Creates a checkbox whose label is specified by str. The state of the checkbox is unchecked.
- Checkbox(String str, Boolean on) throws HeadlessException: It allows you to line the initial state of the checkbox. If one is true, the checkbox is initially checked; otherwise, it’s cleared.
- Checkbox(String str, Boolean on, CheckboxGroup cbGroup) throws HeadlessException or Checkbox(String str, CheckboxGroup cbGroup, Boolean on) throws HeadlessException: It creates a checkbox whose label is specified by str and whose group is specified by cbGroup. If this checkbox isn’t a part of a gaggle, then cbGroup must be null. the worth of on determines the initial state of the checkbox.
Methods of Checkbox
- boolean getState(): To retrieve the present state of a checkbox.
- void setState(boolean on): To line its state, call setState(). Here, if one is true, the box is checked. If it’s false, the box is cleared.
- String getLabel(): you’ll obtain the present label related to a checkbox by calling getLabel().
- void setLabel(String str): To line the label, call setLabel(). The string passed in str becomes the new label related to the invoking checkbox.
Example to understand AWT Checkbox Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet implements ItemListener { String msg = ""; Checkbox winXP, winVista, solaris, mac; public void init () { winXP = new Checkbox ("Windows XP", null, true); winVista = new Checkbox ("Windows Vista"); solaris = new Checkbox ("Solaris"); mac = new Checkbox ("Mac OS"); add (winXP); add (winVista); add (solaris); add (mac); winXP.addItemListener (this); winVista.addItemListener (this); solaris.addItemListener (this); mac.addItemListener (this); } public void itemStateChanged (ItemEvent ie) { repaint (); } // Display current state of the check boxes. public void paint (Graphics g) { msg = "Current state: "; g.drawString (msg, 6, 80); msg = " Windows XP: " + winXP.getState (); g.drawString (msg, 6, 100); msg = " Windows Vista: " + winVista.getState (); g.drawString (msg, 6, 120); msg = " Solaris: " + solaris.getState (); g.drawString (msg, 6, 140); msg = " Mac OS: " + mac.getState (); g.drawString (msg, 6, 160); } }
Output:
CheckboxGroup: Radio Buttons
It is possible to make a group of mutually exclusive checkboxes during which one and just one checkbox up the group are often checked at anybody time. These checkboxes are often called radio buttons because they act just like the station selector on a car radio, only one station is often selected at anybody’s time. To create a group of mutually exclusive checkboxes, you want to first define the group to which they’re going to belong then specify that group once you construct the checkboxes. Checkbox groups are objects of the type CheckboxGroup. Only the default constructor is defined, which creates an empty group.
Creating Radiobutton :
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
CheckboxGroup Methods
- Checkbox getSelectedCheckbox(): You can determine which checkbox in a group is currently selected by calling getSelectedCheckbox().
- void setSelectedCheckbox(Checkbox which): You can set a checkbox by calling setSelectedCheckbox(). Here, is the checkbox that you simply want to be selected. The previously selected checkbox is going to be turned off.
Example to understand AWT CheckboxGroup Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="CBGroup" width=250 height=200> </applet> */ public class RadiobuttonDemo extends Applet implements ItemListener { String msg = ""; Checkbox winXP, winVista, solaris, mac; CheckboxGroup cbg; public void init () { cbg = new CheckboxGroup (); winXP = new Checkbox ("Windows XP", cbg, true); winVista = new Checkbox ("Windows Vista", cbg, false); solaris = new Checkbox ("Solaris", cbg, false); mac = new Checkbox ("Mac OS", cbg, false); add (winXP); add (winVista); add (solaris); add (mac); winXP.addItemListener (this); winVista.addItemListener (this); solaris.addItemListener (this); mac.addItemListener (this); } public void itemStateChanged (ItemEvent ie) { repaint (); } // Display current state of the check boxes. public void paint (Graphics g) { msg = "Current selection: "; msg += cbg.getSelectedCheckbox ().getLabel (); g.drawString (msg, 6, 100); } }
Output:
AWT Choice Control in Java
This component will display a group of times as a drop-down menu from which a user can select only one item. The choice component is used to create a pop-up list of items from which the user may choose. Therefore, Choice control is a form of a menu. When it is inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on a Choice component, the whole list of choices pops up, and a new selection can be made.
Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
- void add(String name): To add a selection to the list, use add(). Here, the name is the name of the item being added.
- String getSelectedItem(): It determines which item is currently selected. It returns a string containing the name of the item.
- int getSelectedIndex(): It determines which item is currently selected. It returns the index of the item.
- int getItemCount(): It obtains the number of items in the list.
- void select(int index): It is used to set the currently selected item with a zero-based integer index.
- void select(String name): It is used to set the currently selected item with a string that will match a name in the list.
- String getItem(int index): It is used to obtain the name associated with the item at the given index. Here, the index specifies the index of the desired items.
Example to understand AWT Choice Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ChoiceDemo" width=300 height=180> </applet> */ public class ChoiceDemo extends Applet implements ItemListener { Choice os, browser; String msg = ""; public void init () { os = new Choice (); browser = new Choice (); // add items to os list os.add ("Windows XP"); os.add ("Windows Vista"); os.add ("Solaris"); os.add ("Mac OS"); // add items to browser list browser.add ("Internet Explorer"); browser.add ("Firefox"); browser.add ("Opera"); browser.add ("Chrome"); // add choice lists to window add (os); add (browser); // register to receive item events os.addItemListener (this); browser.addItemListener (this); } public void itemStateChanged (ItemEvent ie) { repaint (); } // Display current selections. public void paint (Graphics g) { msg = "Current OS: "; msg += os.getSelectedItem (); g.drawString (msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem (); g.drawString (msg, 6, 140); } }
Output:
AWT List Control in Java:
This component will display a group of items as a drop-down menu from which a user can select only one item. The List class provides a compact, multiple-choice, scrolling selection list. Unlike the selection object, which shows only the only selected item within the menu, an inventory object is often constructed to point out any number of choices within the visible window. It also can be created to permit multiple selections.
Creating List : List l = new List(int, Boolean);
List Constructor
- List() throws HeadlessException: It creates a list control that allows only one item to be selected at any one time.
- List(int numRows) throws HeadlessException: Here, the value of numRows specifies the number of entries in the list that will always be visible.
- List(int numRows, boolean multipleSelect) throws HeadlessException: If multipleSelect is true, then the user may select two or more items at a time. If it’s false, then just one item could also be selected.
Method of Lists
- void add(String name): To add a selection to the list, use add(). Here, the name is the name of the item being added. It adds items to the end of the list.
- void add(String name, int index): It also adds items to the list but it adds the items at the index specified by the index.
- String getSelectedItem(): It determines which item is currently selected. It returns a string containing the name of the item. If more than one item is selected, or if no selection has been made yet, null is returned.
- int getSelectedIndex(): It determines which item is currently selected. It returns the index of the item. The first item is at index 0. If more than one item is selected, or if no selection has yet been made, -1 is returned.
- String[] getSelectedItems(): It allows multiple selections. It returns an array containing the names of the currently selected items.
- int[] getSelectedIndexes(): It also allows multiple selections. It returns an array containing the indexes of the currently selected items.
- int getItemCount(): It obtains the number of items in the list.
- void select(int index): It is used to set the currently selected item with a zero-based integer index.
- String getItem(int index): It is used to obtain the name associated with the item at the given index. Here, the index specifies the index of the desired items.
Example to understand AWT List Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ListDemo" width=300 height=180> </applet> */ public class ListDemo extends Applet implements ActionListener { List os, browser; String msg = ""; public void init () { os = new List (4, true); browser = new List (4, false); // add items to os list os.add ("Windows XP"); os.add ("Windows Vista"); os.add ("Solaris"); os.add ("Mac OS"); // add items to browser list browser.add ("Internet Explorer"); browser.add ("Firefox"); browser.add ("Opera"); browser.select (1); // add lists to window add (os); add (browser); // register to receive action events os.addActionListener (this); browser.addActionListener (this); } public void actionPerformed (ActionEvent ae) { repaint (); } // Display current selections. public void paint (Graphics g) { int idx[]; msg = "Current OS: "; idx = os.getSelectedIndexes (); for (int i = 0; i < idx.length; i++) msg += os.getItem (idx[i]) + " "; g.drawString (msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem (); g.drawString (msg, 6, 140); } }
Output:
AWT Scroll Bar Control in java
Scrollbars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is really a composite of several individual parts. Each end has an arrow that you simply can click to get the present value of the scroll bar one unit within the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values are indicated by the slider box for the scroll bar. Scrollbars are encapsulated by the Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();
Scrollbar Constructor
- Scrollbar() throws HeadlessException: It creates a vertical scrollbar.
- Scrollbar(int style) throws HeadlessException: It allows you to specify the orientation of the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar is created. If a style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
- Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws HeadlessException: Here, the initial value of the scroll bar is passed in initialValue. The number of units represented by the peak of the thumb is passed in thumbSize. The minimum and maximum values for the scroll bar are specified by min and max.
Scrollbar Methods
- void setValues(int initialValue, int thumbSize, int min, int max): It is used to set the parameters of the constructors.
- int getValue(): It is used to obtain the current value of the scroll bar. It returns the current setting.
- void setValue(int newValue): It is used to set the current value. Here, newValue specifies the new value for the scroll bar. When you set a worth, the slider box inside the scroll bar is going to be positioned to reflect the new value.
- int getMaximum(): It is used to retrieve the minimum values. They return the requested quantity. By default, 1 is the increment added to the scroll bar.
- int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the increment subtracted from the scroll bar.
Example to understand AWT Scrollbar Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="SBDemo" width=300 height=200> </applet> */ public class ScrollbarDemo extends Applet implements AdjustmentListener, MouseMotionListener { String msg = ""; Scrollbar vertSB, horzSB; public void init () { int width = Integer.parseInt (getParameter ("width")); int height = Integer.parseInt (getParameter ("height")); vertSB = new Scrollbar (Scrollbar.VERTICAL, 0, 1, 0, height); horzSB = new Scrollbar (Scrollbar.HORIZONTAL, 0, 1, 0, width); add (vertSB); add (horzSB); // register to receive adjustment events vertSB.addAdjustmentListener(this); horzSB.addAdjustmentListener(this); addMouseMotionListener (this); } public void adjustmentValueChanged (AdjustmentEvent ae) { repaint (); } //Update scroll bars to reflect mouse dragging. public void mouseDragged (MouseEvent me) { int x = me.getX (); int y = me.getY (); vertSB.setValue (y); horzSB.setValue (x); repaint (); } //Necessary for MouseMotionListener public void mouseMoved (MouseEvent me) { } //Display current value of scroll bars. public void paint (Graphics g) { msg = "Vertical: " + vertSB.getValue (); msg += ", Horizontal: " + horzSB.getValue (); g.drawString (msg, 6, 160); //show current mouse drag position g.drawString ("*", horzSB.getValue (), vertSB.getValue ()); } }
Output
AWT TextComponent Control in Java
The TextComponent class is the superclass of any component that permits the editing of some text. A text component embodies a string of text. The TextComponent class defines a group of methods that determine whether or not this text is editable. There are two types of TextComponent:
- TextField
- TextArea
AWT TextField Control in Java
The TextField component will allow the user to enter some text. It is used to implement a single-line text-entry area, usually called an edit control. It also allows the user to enter strings and edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent.
Creating TextField : TextFielf tf = new TextField(size);
TextField Constructors
- TextField() throws HeadlessException: It creates a default textfield.
- TextField(int numChars) throws HeadlessException: It creates a text field that is numChars characters wide.
- TextField(String str) throws HeadlessException: It initializes the text field with the string contained in str.
- TextField(String str, int numChars) throws HeadlessException: It initializes a text field and sets its width.
TextField Methods
- String getText(): It is used to obtain the string currently contained in the text field.
- void setText(String str): It is used to set the text. Here, str is the new String.
- void select(int startIndex, int endIndex): It is used to select a portion of the text under program control. It selects the characters beginning at startIndex and ending at endIndex-1.
- String getSelectedText(): It returns the currently selected text.
- boolean isEditable(): It is used to determine editability. It returns true if the text may be changed and false if not.
- void setEditable(boolean canEdit): It is used to control whether the contents of a text field may be modified by the user. If canEdit is true, the text may be changed. If it is false, the text cannot be altered.
- void setEchoChar(char ch): It is used to disable the echoing of the characters as they are typed. This method specifies a single character that TextField will display when characters are entered.
- boolean echoCharIsSet(): By this method, you can check a text field to see if it is in this mode.
- char getEchochar(): It is used to retrieve the echo character.
Example to understand AWT TextFiled Control in Java:
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="TextFieldDemo" width=380 height=150> </applet> */ public class TextfieldDemo extends Applet implements ActionListener { TextField name, pass; public void init () { Label namep = new Label ("Name: ", Label.RIGHT); Label passp = new Label ("Password: ", Label.RIGHT); name = new TextField (12); pass = new TextField (8); pass.setEchoChar ('?'); add (namep); add (name); add (passp); add (pass); //register to receive action events name.addActionListener (this); pass.addActionListener (this); } //User pressed Enter. public void actionPerformed (ActionEvent ae) { repaint (); } public void paint (Graphics g) { g.drawString ("Name: " + name.getText (), 6, 60); g.drawString ("Selected text in name: " + name.getSelectedText (), 6, 80); g.drawString ("Password: " + pass.getText (), 6, 100); } }
Output
Here, you will get a response when the user will press ENTER.
AWT TextArea Control in Java
Sometimes one line of text input isn’t enough for a given task. To handle these situations, the AWT includes an easy multiline editor called TextArea.
Creating TextArea : TextArea ta = new TextArea();
TextArea Constructor
- TextArea() throws HeadlessException: It creates a default textarea.
- TextArea(int numLines, int numChars) throws HeadlessException: It creates a text area that is numChars characters wide. Here, numLines specifies the height, in lines of the text area.
- TextArea(String str) throws HeadlessException: It initializes the text area with the string contained in str.
- TextArea(String str, int numLines, int numChars) throws HeadlessException: It initializes a text field and sets its width. Initial text can be specified by str.
- TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException: Here, you can specify the scroll bars that you want the control to have. sBars must be one of these values :
- SCROLLBARS_BOTH
- SCROLLBARS_NONE
- SCROLLBARS_HORIZONTAL_ONLY
- SCROLLBARS_VERTICAL_ONLY
TextArea Methods
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in the TextField section. TextArea adds the following methods:
- void append(String str): It appends the string specified by str to the end of the current text.
- void insert(String str, int index): It inserts the string passed in str at the specified index.
- voidReplaceRange(String str, int startIndex, int endIndex): It is used to replace the text. It replaces the characters from startIndex to endIndex-1.
Example to understand AWT TextArea Control in Java:
import java.awt.*; import java.applet.*; /* <applet code="TextAreaDemo" width=300 height=250> </applet> */ public class TextAreaDemo extends Applet { public void init() { String val = "Java SE 6 is the latest version of the most\n" + "widely-used computer language for Internet programming.\n" + "Building on a rich heritage, Java has advanced both\n" + "the art and science of computer language design.\n\n" + "One of the reasons for Java's ongoing success is its\n" + "constant, steady rate of evolution. Java has never stood\n" + "still. Instead, Java has consistently adapted to the\n" + "rapidly changing landscape of the networked world.\n" + "Moreover, Java has often led the way, charting the\n" + "course for others to follow."; TextArea text = new TextArea(val, 10, 30); add(text); } }
Output
In the next article, I am going to discuss Event Handling in Java with examples. Here, in this article, I try to explain AWT Controls in Java with Examples. I hope you enjoy this AWT Controls in Java with Examples article.
it is useful
nice
thank you