Showing posts with label Abstract Window Toolkit. Show all posts
Showing posts with label Abstract Window Toolkit. Show all posts

Monday, 18 November 2013

Get Global Mouse Pointer Location in Java in One Statement

global mouse location
Here is how to get global mouse pointer location in Java using a single statement. Yes, you heard it right, in a single statement!!

import java.awt.*;
class GetPointerLoc
{
    public static void main(String args[])
    {
    // Get global current cursor location
    Point p=MouseInfo.getPointerInfo().getLocation();
   
    System.out.println(p);
    }
}

getLocation(): This method is present in the java.awt.PointerInfo class. The object for this class can be created using the getPointerInfo() method in the java.awt.MouseInfo class.
Image credit: Iconarchive

Move Mouse Pointer with Arrow Keys in Java

moving mouseYes, you are able to move mouse pointer with arrow keys in Java globally and that is theme of the below program. With the help of this program, the cursor pointer goes up when UP arrow key is pressed, down when down arrow key is pressed.... and press the mouse when enter is pressed. Isn't that cool? Let us take a look at the example below.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MoveCursor extends JFrame
{
Robot r;

    public MoveCursor()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Move Cursor with Keyboard");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // hide the visibility
        setUndecorated(true);
        setOpacity(0f);
        setVisible(true);
       
        // Create Robot object
        try
        {
        r=new Robot();
        }catch(Exception e){}
       
        addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e)
            {
                // If there occured an exception
                // while creating Robot object, r is null
                // then go back
                if(r==null) return;
               
                // Get global current cursor location
                Point p=MouseInfo.getPointerInfo().getLocation();
               
                switch(e.getKeyCode())
                {
                    case KeyEvent.VK_UP: r.mouseMove(p.x,p.y-1); break;
                    case KeyEvent.VK_DOWN: r.mouseMove(p.x,p.y+1); break;
                    case KeyEvent.VK_LEFT: r.mouseMove(p.x-1,p.y); break;
                    case KeyEvent.VK_RIGHT: r.mouseMove(p.x+1,p.y); break;
                    // left click
                    case KeyEvent.VK_ENTER: r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseRelease(MouseEvent.BUTTON1_MASK);
                }
            }
        });
    }
   
    public static void main(String args[])
    {
        new MoveCursor();
    }
}
MouseInfo.getPointerInfo().getLocation(): This method is present in the PointerInfo class whose object can be obtained by getPointerInfo() method in the MouseInfo class. getLocation() returns the current mouse pointer location which is helpful in moving the cursor with arrow keys.

Wednesday, 6 November 2013

Java AWT Tutorial for Beginners

Java AWT Tutorial for Beginners
Here is an exhaustive AWT tutorial in Java for beginners. This tutorial covers introduction to the AWT, its components, advantages and drawbacks. You can find the Java Event Handling tutorial here.

Introduction to the AWT

AWT (a.k.a Abstract Window Toolkit) is a concept designed for building simple GUIs in Java applications (both applets and desktop). AWT is introduced in the year 1995 when Java was first introduced. It comes with a thin layer of components with a small learning curve when compared to that of the Swing. As creating GUI components need, operating system support, AWT components are developed in native code. This is the reason why AWT components look different on different operating systems thereby ruining the Java paradigm Write once, run anywhere. The code runs anywhere, but not in the desired way. Just like Swing, AWT is not thread safe meaning, it doesn't run effectively (or in the desired way) on other threads. A separate thread called the Event dispatch thread runs the GUI part while other background processes are carried out by other threads such as the main thread for better performance.

Why do we need GUI over CUI?

Before we get into the AWT, it is important to know the advantages of building GUI applications over CUI apps.
1. GUI applications are user-friendly, they don't require user to have knowledge of commands (like in the DOS).
2. GUI applications support multi tasking which means that the users can perform various tasks (in other words, work with several apps) at a time. For example, he can listen to music in foobar and play an NFS game. In a CUI, you need a command to complete before executing another command.
3. In CUI you can only see text, where as in GUIs you can see images, videos and flash.

Examples of GUI include Windows XP, Mac OS X, Ubuntu and those of CUI include DOS etc.

AWT Class hierarchy

The ultimate super class of all the GUI components both in AWT as well as Swing is the java.awt.Component. An immediate sub-class of it is the Container class. So every container is a component (from inheritance). Before learning the hierarchy, let us see what is a component and a container.

A component refers to a GUI control such as Button, Label etc.
A container refers to a GUI control that is capable of containing other GUI controls in it. Typical examples include a Frame, Panel, Dialog etc.


Component

        |

        +-- Container

                    |

                    +-- Panel

                    |        |

                    |        +-- Applet

                    |

                    +-- Window

                            |

                            +-- Frame

Component class and its sub classes

Component class is an immediate sub class of the Object. The other immediate sub classes include Label, Button, Checkbox, Choice, List, Canvas, Scrollbar and TextComponent.

Window class

A window in AWT is a container represents a top-level window that doesn't have a title bar (so it doesn't have close, minimize, maximize buttons), menu bar. This sits on the desktop directly and has a BorderLayout by default.

Frame class

It is a sub class of Window class which has a title bar, menu bar, borders and is re-sizable with border layout by default. This is what we use in our programs to create windows.
  1. Creating an AWT Frame in the easy way 

Panel class 

It is a sub class of the Container class. It is a border less window that doesn't contain any title bar or menubar. usually added to another container like the Frame. The main purpose of a panel is to group components. It comes with a default FlowLayout.
  1. Creating an AWT Panel in Java

Label class

A label is an informatory GUI component that typically describes another component. For example, you see a label Username side of a username field to tell you that the textfield is for typing username.
  1. Creating Labels in AWT

Button class

A Button is the most common GUI control that lets you click on it do some action. You might already have seen it a lot of times, in OK and Cancel buttons, for example.
  1. Creating an AWT Button in Java

TextField class

A TextField can contain a single row text. It is mostly used for single line data. You already have seen it in lot of username fields and even in the subscribe field in the blog sidebar. It is a sub class of TextComponent
  1. 4 Ways to Create an AWT TextField

TextArea class

A TextArea can contain multiple rows of text. You might have seen it in Notepad, that's where you write text. As it contains multiple rows and columns, it contains scrollbars.
  1. AWT TextArea in Java - All methods and constructors

Checkbox class

A checkbox allows user to check or un check an option. Users can check multiple checkboxes. However, you can also use checkbox as a radio button (which restricts user to select only one out of various checkboxes) if several checkboxes are added to a group. All these are covered in the below example.
  1. 5 Ways to Create an AWT Checkbox

Choice class

A Choice allows user to choose an item from a list of similar items. It is a drop down menu also called as a combo box (in swing) and only one item is visible before drop down.
  1. Creating an AWT Choice in Java

List class

A List unlike a Choice allows user to select multiple items, however there is also an option to restrict to a single selection. But a list looks different, all items are visible in the List.
  1. Create an AWT List in Java

Working with Menus

A MenuBar is a component that contains menus. A Menu contains MenuItems and other menus. If A menu contains B Menu then B Menu is said to be a sub menu of A Menu.
  1. Creating Menus and MenuItems in AWT Example

CheckboxMenuItem class

A CheckboxMenuItem is a MenuItem that can be checked or un-checked. You might have encountered it in Notepad > Format > Wordwrap
  1. CheckboxMenuItem in AWT Example

Dialog class

A dialog is a window with a title bar but with no minimize or maximize options. It is a direct sub-class of Window and comes with default BorderLayout. You can also remove the title bar as you can in Frame. Also, a dialog can be constructed with a parent, typically a Frame or another dialog.
Dialogs are divided into types, Modal and Modeless (default). A modal dialog blocks user input of top-level windows of the dialog (i.e. its parents, but not its children) while a modeless dialog doesn't. Like the Frame, dialogs can generate WindowEvent.
  1. AWT Dialog in Java Example

FileDialog class

A FileDialog is a dialog that lets user select a file either for opening or saving. You can see it when you click open/save as in Notepad. It is modal by default, which means that it blocks user input until user selects a file or closes it.
  1. Example on AWT FileDialog

Accessing System tray

You can also access system tray in AWT. You can create an icon and set a popup menu for it.
  1. Access system tray in AWT

AWT Toolkit Features

The java.awt.Toolkit class contains methods with which we can do a lot of things to do some basic tweaks.
  1. Create a Beep sound in Java 
  2. Get all installed fonts in a PC 
  3. Get data from Clipboard in Java 
  4. Get screen size and resolution in Java 

Robot class

Robot class in Java is designed to automate tasks. It contains methods to programatically perform user actions like pressing, releasing keys, clicking mouse button.
  1. How to take a screenshot using Robot?
  2. Using Robot class in Java AWT

Desktop and GraphicsConfiguration classes

Desktop class is used to work with applications installed in Windows. It can be used to open files, url etc. The specialty of this class over Runtime and ProcessBuilder is that, it launches any file in the default application so we don't need to specify. GraphicsConfiguration gives details about output devices like monitor.
  1. Open a URL in Java
  2. Get screen center point in Java
Thanks for reading the post. This post will be updated with a lot of new examples on different topics in the Java AWT. So stay tuned!

AWT Dialog in Java Example

This exhaustive example illustrates creating an AWT Dialog. This tutorial also covers all core methods of the java.awt.Dialog class.

import java.awt.*;
import java.awt.geom.*;
class AWTDialog extends Frame
{
Dialog d1,d2;

    public AWTDialog()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("AWT Dialog in Java Example");
       
        // A dialog with current frame as parent
        d1=new Dialog(this);
       
        // Set the title
        d1.setTitle("Dialog 1");
       
        d1.setSize(400,400);
       
        // Hide title bar and borders
        d1.setUndecorated(true);
       
        // Set background for dialog
        d1.setBackground(Color.GRAY);
       
        // Set opacity
        d1.setOpacity(0.4f);
       
        // Set d1 location relative to desktop
        // d1 appears at center of screen
        d1.setLocationRelativeTo(null);
       
        // Set some shape to d1
        RoundRectangle2D.Double r=new RoundRectangle2D.Double(0,0,400,400,20,20);
       
        // Set the rounded rectangle shape
        d1.setShape(r);
       
        d1.setVisible(true);
       
        // Create a dialog with current frame as parent
        // with title Simple Dialog
        d2=new Dialog(d1,"Simple Dialog");
       
        // d1 cannot be made active if d2 isn't closed
        // this is theme behind setting a dialog modal
        // default value is false
        d2.setModal(true);
       
        // Set size
        d2.setSize(150,150);
       
        // Set layout
        d2.setLayout(new FlowLayout());
       
        // Make it non resizable
        d2.setResizable(false);
       
        // Set d2 location relative to d1
        // d2 appears at center of d1
        d2.setLocationRelativeTo(d1);
       
        // Add some components
        d2.add(new Button("Button"));
        d2.add(new Checkbox("Checkbox"));
        d2.add(new TextField(20));
       
        // Show the dialog
        d2.setVisible(true);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTDialog();
    }
}

AWTDialog(): Code illustrating AWT Dialog is invoked here.

Creating an AWT Dialog in Java

CheckboxMenuItem in AWT Example

The following example illustrates CheckboxMenuItem in AWT. This tutorials covers all core methods of the java.awt.CheckboxMenuItem class.

import java.awt.*;
import java.awt.event.*;
class AWTCheckboxMenuItem extends Frame
{
MenuBar b;
Menu m;
CheckboxMenuItem m1,m2,m3;

    public AWTCheckboxMenuItem()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("CheckboxMenuItem in AWT Example");
        setLayout(new FlowLayout());
       
        // Create menu bar and menu
        b=new MenuBar();
        m=new Menu("Menu");
       
        // Empty checkboxmenuitem
        m1=new CheckboxMenuItem();
       
        // Labeled
        m2=new CheckboxMenuItem("Item 2");
       
        // Selected and labeled
        m3=new CheckboxMenuItem("Item 3",true);
       
        // Set label and state
        m1.setLabel("Item 1");
        m1.setState(true);
       
        // Add CheckboxMenuItems to menu
        m.add(m1);
        m.add(m2);
        m.add(m3);
       
        // Add menu to menubar
        b.add(m);
       
        // Add menu to the menubar
        setMenuBar(b);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTCheckboxMenuItem();
    }
}

AWTCheckboxMenuItem(): Code illustrating CheckboxMenuItem in AWT is invoked here.
Also see ItemListener for CheckboxMenuItem

CheckboxMenuItem in AWT Example
Previous: Creating Menus and MenuItems in AWT

3 Ways to Create an AWT List in Java

The following illustrates creating an AWT List in Java. This tutorial also covers all core methods of the java.awt.List class.

import java.awt.*;
import java.awt.event.*;
class AWTList extends Frame
{
List l1,l2,l3,l4;

    public AWTList()
    {
        createAndShowGUI();
    }
  
    private void createAndShowGUI()
    {
        setTitle("List in AWT Example");
        setLayout(new FlowLayout());
      
        // An empty list
        l1=new List();
      
        // List with given no.of rows
        l2=new List(5);
      
        // List with given no.of rows,multi-select enabled
        l3=new List(5,true);
      
        // One more empty list!
        l4=new List();
      
        // Add items
        l1.add("Item 1");
        l1.add("Item 2");
        l1.add("Item 3");
        l1.add("Item 4");
        l1.add("Item 5");
      
        l2.add("Item 1");
        l2.add("Item 2");
        l2.add("Item 3");
        l2.add("Item 4");
        l2.add("Item 5");
      
        l3.add("Item 1");
        l3.add("Item 2");
        l3.add("Item 3");
        l3.add("Item 4");
        l3.add("Item 5");
      
        l4.add("Item 1");
        l4.add("Item 2");
        l4.add("Item 3");
        l4.add("Item 4");
        l4.add("Item 5");
      
        // Enable multi select for l1
        l1.setMultipleMode(true);
      
        // Add item at index 2
        // Item 3 goes to 4th 'position'
        l1.add("Item 2-A",2);
      
        // Make Item 1 visible no matter what
        // which item is selected
        l1.makeVisible(0);
      
        // Replace an item
        // Item 2 becomes 2nd Item
        l3.replaceItem("2nd Item",1);
      
        // Select item at 2nd index
        l1.select(2);
      
      
        /* -- Select and de-select -- */
      
        // Select item at 0 index
        l2.select(0);
      
        // De-Select an item by index
        l2.deselect(0);
      
        // Remove item at 2nd index
        l2.remove(2);
      
        // Remove Item 1
        // Item 2 now comes at 0th index
        l3.remove("Item 1");
      
        // Remove all items in l4
        l4.removeAll();
      
        // Print get methods
        System.out.println("Item at index 0 in l1 is "+l1.getItem(0));
        System.out.println("Visible index for l1 is "+l1.getVisibleIndex());
        System.out.println("No.of rows of l2 is "+l2.getRows());
        System.out.println("No.of items in l3 is "+l3.getItemCount());
        System.out.println("Is 0 index selected in l3? "+l1.isIndexSelected(0));
        System.out.println("Is multi select enabled in l2? "+l1.isMultipleMode());

      
        // Add all lists
        add(l1);
        add(l2);
        add(l3);
        add(l4);
      
        setSize(400,400);
        setVisible(true);
    }
  
    public static void main(String args[])
    {
        new AWTList();
    }
}

AWTList(): Code illustrating creating an AWT List in Java is invoked here.
new AWTList(): Create an object for the AWTList class.

You might also want to see using ItemListener for AWT List

Creating AWT List in Java

Next: Create Menus and MenuItems in AWT
Previous: Creating an AWT Choice in Java

Creating an AWT Choice in Java

The following example illustrates creating an AWT Choice. This tutorial will also cover all the core methods of the java.awt.Choice class.

import java.awt.*;
import java.awt.event.*;
class AWTChoice extends Frame
{
Choice c,h,r;

    public AWTChoice()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Choice in AWT Example");
        setLayout(new FlowLayout());
       
        // First, create a choice
        c=new Choice();

        // Add items
        c.add("Apple");
        c.add("Mango");
        c.add("Orange");
        c.add("Grapes");
        c.add("Strawberry");
        c.add("Strawberry");
       
        // Set a selected index, default is 0
        c.select(2);
       
        // Insert item at give index
        c.insert("Guava",3);
       
        // Remove the first Strawberry
        c.remove("Strawberry");
       
        // This is another choice
        h=new Choice();
       
        // Add items to h
        h.addItem("Vanilla");
        h.addItem("Chocolate");
        h.addItem("Butterscotch");
        h.addItem("Strawberry");
       
        // Remove an item at given index
        h.remove(2);
       
        // Select Strawberry (case-senstive!!)
        h.select("Strawberry");
       
        // One more, last one!
        r=new Choice();
       
        // Add items
        r.add("Item 1");
        r.add("Item 2");
        r.add("Item 3");
        r.add("Item 4");
       
        // Now, remove all!
        r.removeAll();
       
        // Add choices
        add(c);
        add(h);
        add(r);
       
        // Print get methods
        System.out.println("Selected index in c "+c.getSelectedIndex());
        System.out.println("Selected item in h "+h.getSelectedItem());
        System.out.println("No.of items in r "+r.getItemCount());
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTChoice();
    }
}

Also see Creating ItemListener for AWT Choice

Creating AWT Choice in Java

Next: Creating AWT List in Java
Previous: 5 Ways to Create an AWT Checkbox

5 Ways to Create an AWT Checkbox

The following example illustrates creating an AWT Checkbox using its five constructors. This tutorial will also cover all the core methods of the Checkbox class.

import java.awt.*;
import java.awt.event.*;
class AWTCheckbox extends Frame
{
Checkbox c1,c2,c3,c4,c5;
CheckboxGroup cg;

    public AWTCheckbox()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Checkbox in AWT Demo");
        setLayout(new FlowLayout());
       
        // Create a group
        // Checkboxes in a group become
        // radio buttons
        cg=new CheckboxGroup();
       
        // No label, not selected
        c1=new Checkbox();
       
        // Labeled and not selected
        c2=new Checkbox("Checkbox 2");
       
        // Labeled and selected
        c3=new Checkbox("Checkbox 3",true);
       
        // -- Radio buttons -- //
       
        // Labeled, selected and in cg group
        c4=new Checkbox("Checkbox 4",true,cg);
       
        // Same as above but parameter shift
        c5=new Checkbox("Checkbox 5",cg,true);
       
        // Set to a checkbox group
        // Now c3 becomes a radio button
        c3.setCheckboxGroup(cg);
       
        // -- Other methods -- //
       
        // Set label
        c1.setLabel("Checkbox 1");
       
        // Set state
        c2.setState(true);
       
        // Add all checkboxes
        add(c1);
        add(c2);
        add(c3);
        add(c4);
        add(c5);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTCheckbox();
    }
}

In the above example, c4 and c5 are set selected but as they belong to a group and that only one checkbox in a group has to be selected, the checkbox whose state is set last will come selected in AWT, so is c5 selected. You might also want to check out using ItemListener for Checkbox.

AWTCheckbox(): Code illustrating creating AWT Checkbox is written here.

Creating an AWT Checkbox in Java
Next: Creating AWT Choice in Java
Previous: Creating AWT TextArea in Java

4 Ways to Create an AWT TextField

The following example illustrates creating an AWT TextField using its four constructors. This tutorial will also cover all core methods of TextField class.

import java.awt.*;
class AWTTextField extends Frame
{
TextField t1,t2,t3,t4;

    public AWTTextField()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextField in AWT Demo");
        setLayout(new FlowLayout());
       
        t1=new TextField();
        t2=new TextField(20);
        t3=new TextField("Third textfield");
        t4=new TextField("Fourth textfield",40);
       
        // Set max visible chars
        t1.setColumns(25);
       
        // Set echo char (for password fields)
        t2.setEchoChar('*');
       
        // Set text
        t1.setText("First textfield");
       
        // Select all
        t3.selectAll();
       
        // Set position of caret   
        t4.setCaretPosition(2);
       
        // Make t1 non-editable
        t1.setEditable(false);
       
        // Set custom background,foreground
        t1.setBackground(Color.LIGHT_GRAY);
        t1.setForeground(Color.RED);
       
        // Add all textfields
        add(t1);
        add(t2);
        add(t3);
        add(t4);
       
        // Print textfield properties
        System.out.println("Is t1 editable? "+t1.isEditable());
        System.out.println("Is echo char set for t1? "+t1.echoCharIsSet());
        System.out.println("Echo char for t2 "+t2.getEchoChar());
        System.out.println("Selected text in t3 "+t3.getSelectedText());
        System.out.println("Caret position in t4 "+t4.getCaretPosition());
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTTextField();
    }
}

AWTTextField(): Code illustrating creation of AWT TextField is invoked here.
new AWTTextField(): Create an object for the class AWTTextField

4 Ways to Create an AWT TextField in Java
Next: Creating AWT TextArea in Java
Previous: Creating an AWT Button