Showing posts with label abstract window toolkit. Show all posts
Showing posts with label abstract window toolkit. Show all posts

Spring Hibernate Open URL in Java using Default Browser

An example of browsing a web URL in java using the default web browser.


Example


import java.awt.Desktop;
import java.net.URI;
class BrowseURL
{
public static void main(String args[]) throws Exception
{

// Create Desktop object
Desktop d=Desktop.getDesktop();

// Browse a URL, say google.com
d.browse(new URI("http://google.com"));

}
}

Try it yourself! It works! The default handler for http:// protocol will be given the address to open.

Spring Hibernate Creating Labels in AWT using the Label class

The following example illustrates working with AWT Labels which are mostly used for demonstration purposes.

import java.awt.*;
class LabelDemo extends Frame
{
Label l1,l2;
    public LabelDemo()
    {
    setTitle("Label Demo");
    setLayout(new FlowLayout());
    setVisible(true);
   
    // Create labels
    l1=new Label("I am first label.");
    l2=new Label("I am second label.");
   
    // Add labels
    add(l1);
    add(l2);

    //pack the frame
    pack();
    }
    public static void main(String args[])
    {
    new LabelDemo();
    }
}

Notes: You can also create AWT Labels using the other constructors.
  • If you use the default constructor Label() then you can set the text by calling the setText(String text) method.
  • If you use the third constructor Label(String text, int alignment) then you can also set the alignment for the label. Possible alignments are Label.LEFT, Label.RIGHT, Label.CENTER
  • The second constructor as shown in the above example is mostly used. To align the label to a position you can call the setAlignment(int alignment) method.

Java J2EE Spring Introduction to Java Swings

Well, finally I have begun writing articles for these topics on Advanced Java Concepts. We begin with the first part, which is UI Programming with Java Swings. This chapter is just an introduction to this great technology.

So, lets get started!!!

Before Java Swings – Abstract Window Toolkit (AWT)

When Java 1.0 was introduced, it contained a class library, which Sun called the Abstract

Spring Hibernate Access System Tray in AWT

Now, create tray icons on the Windows Taskbar with AWT. The java.awt.SystemTray and java.awt.TrayIcon are the classes that help you. The following example illustrates it.



See how the code goes!

AWT System Tray Window

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AWTSystemTray extends JFrame
{
JButton jb;
SystemTray tray;
TrayIcon t;

public AWTSystemTray()
{
setTitle("AWT System Tray");
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

jb=new JButton("Hide");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
tray=SystemTray.getSystemTray();
t=new TrayIcon(new ImageIcon("C:\\Users\\Computer\\Downloads\\icon11.jpg").getImage());
t.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me)
{
if(me.getButton()==MouseEvent.BUTTON1)
{
setVisible(true);
tray.remove(t);
}
}
});

try
{
PopupMenu m=new PopupMenu();
MenuItem exit=new MenuItem("Exit");
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
System.exit(0);
}
});

m.add(exit);

MenuItem remove=new MenuItem("Hide Icon");
remove.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
tray.remove(t);
setVisible(true);
}
});

m.add(remove);

t.setPopupMenu(m);

tray.add(t);

setVisible(false);

}catch(Exception e){}
}
});

add(jb);
}

public static void main(String args[])
{
new AWTSystemTray();
}
}

SystemTray in AWT - Explanation


jb=new JButton("Hide"): Create a new JButton with text Hide

When JButton is clicked..


tray=SystemTray.getSystemTray(): This is a method of the java.awt.SystemTray class which returns a java.awt.SystemTray object with which we can add tray icons to the system tray. You'll have to note that not all Operating systems support system tray.

t=new TrayIcon(new ImageIcon("C:\\Users\\Computer\\Downloads\\icon11.jpg").getImage()): This constructor in java.awt.TrayIcon class takes java.awt.Image as parameter which points out the image to be displayed as icon in the system tray. For this, i've used javax.swing.ImageIcon class which has a constructor that takes java.lang.String as parameter which represents the path of the image file. The javax.swing.ImageIcon consists of a method called getImage() which returns a java.awt.Image object pointing to the image specified (here the image is icon11.jpg and the path is specified above).

What if user clicks on Tray icon?


me.getButton(): This method returns the button which the user has clicked ex. left click or right click... MouseEvent.BUTTON1 represents left click.

setVisible(true): Make the frame visible. This is done when user left-clicks on the tray icon.

tray.remove(t): Remove tray icon. When frame is visible, i don't need a tray icon. That's why i've removed it.

p=new PopupMenu(): Create a popup menu, the menu that appears when user right-clicks on any component to which it is added.

System.exit(0): Exit the program when the user clicks on menu item exit

tray.remove(t): Remove icon from the tray, when the user clicks on menu item remove (which has text Hide Icon) on it.

setVisible(true): When icon is no more, the frame has to visible, else the user will suffer.

t.setPopupMenu(m): Set the popup menu named m which contains menu items exit,remove to the TrayIcon. (Right click on the tray icon to see this menu)

tray.add(t): Add the tray icon t to tray.

setVisible(false): When tray icon is visible, i don't need the frame to be visible. Make either one visible.

Also see..
  1. Creating JButtons in Swing
External links that may help you..

Spring Framework How to take a screenshot using Robot

Java Cup
Here is an example on taking a screenshot in Java using the AWT Robot class which is earlier discussed in this blog. You do not need to write tonnes and tonnes of code to do this, it is just a method far way. The method that does the thing is createScreenCapture() present in java.awt.Robot class. Here is it's prototype.




BufferedImage createScreenCapture(Rectangle rect)

This method takes java.awt.Rectangle as parameter. You can use any of the seven constructors of this class to create it's object, however i don't recommend the first one which just creates a Rectangle object that is invisible when used to capture the screen. All the constructors do the same thing, their parameters differ instead. For brevity and ease, in this post i will be using the third constructor which takes 4 integer values which represent the x, y, width, height respectively. The returned java.awt.image.BufferedImage object is returned. This is used to write the image to a file. Here is the example.


import java.util.*;

import java.awt.*;

import java.awt.image.*;

import javax.imageio.*;

import java.io.*;

class ScreenCapture

{

public static void main(String args[]) throws Exception

{

// Throws AWTException

Robot rb=new Robot();



Scanner s=new Scanner(System.in);

System.out.println("Enter the x,y,width,height of capture");

int x=s.nextInt();

int y=s.nextInt();



int width=s.nextInt();

int height=s.nextInt();



String file=s.next();



// Get the BufferedImage object for writing to a fiel

BufferedImage bim=rb.createScreenCapture(new Rectangle(x,y,width,height));



/* Throws IOException

* Write in PNG format. You can choose whatever format you want.

* Write the image.

* If you know the extension of the format.

* Write to a file specified

*/

ImageIO.write(bim,"PNG",new File(file));

}

}

Sample output of ScreenCapture

Creating ScreenShot in Java using Robot class

Spring Hibernate Using ItemListener for AWT List

The following example illustrates use of ItemEvent with AWT List
import java.awt.*;
import java.awt.event.*;
class ListAction extends Frame
{
List list;
Label label;
    public ListAction()
    {
   
    // Set frame properties
    setTitle("List with ItemListener Demo");
    setSize(400,400);
    setLayout(new FlowLayout());
    setLocationRelativeTo(null);
    setVisible(true);
   
    // Create List
    list=new List();
   
    // Create label
    label=new Label();
   
    // Add items
    list.add("Apple");
    list.add("Mango");
    list.add("Guava");
    list.add("Orange");
    list.add("Pineapple");
    list.add("Grapes");
   
    // Add List
    add(list);
   
    // Add label
    add(label);
   
    // Add item listener
    list.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent ie)
        {
        label.setText("You selected "+list.getSelectedItem());
        }
    });
   
    }
    public static void main(String args[])
    {
    new ListAction();
    }
}
ListAction() : Code illustrating ItemListener with AWT List is written here
new ListAction() : Create object for the class ListAction

 

Spring Hibernate Create ItemListener for AWT Choice

ItemListener catches ItemEvent. The following example illustrates it.
import java.awt.*;
import java.awt.event.*;
class ChoiceAction extends Frame
{
Choice c;
Label l;
    public ChoiceAction()
    {
   
    // Set frame properties
    setTitle("Choice with ItemListener Demo");
    setSize(400,400);
    setLayout(new FlowLayout());
    setLocationRelativeTo(null);
    setVisible(true);
   
    // Create choice
    c=new Choice();
   
    // Create label
    l=new Label();
   
    // Add items
    c.add("Apple");
    c.add("Mango");
    c.add("Guava");
    c.add("Orange");
    c.add("Pineapple");
    c.add("Grapes");
   
    // Add choice
    add(c);
   
    // Add label
    add(l);
   
    // Add item listener
    c.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent ie)
        {
        l.setText("You selected "+c.getSelectedItem());
        }
    });
   
    }
    public static void main(String args[])
    {
    new ChoiceAction();
    }
}
ChoiceAction() : Code illustrating item listener on Choice is written here
new ChoiceAction() : Create the object for the class ChoiceAction


Spring Hibernate Create ActionListener for AWT Button


The following code illustrates using Action Listener with AWT Button.

import java.awt.*;
import java.awt.event.*;
class ButtonAction extends Frame
{
Button b1,b2,b3;
Frame thisFrame;
public ButtonAction()
{
// Set the frame properties
setTitle("Button with ActionListener Demo");
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
// Assign current object
thisFrame=this;
// Create buttons
b1=new Button("Minimize");
b2=new Button("Maximize/Restore");
b3=new Button("Exit");
// Add buttons
add(b1);
add(b2);
add(b3);
// Add action listeners to buttons
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
setState(Frame.ICONIFIED);
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(thisFrame.getExtendedState()==Frame.NORMAL)
setExtendedState(Frame.MAXIMIZED_BOTH);
else if(thisFrame.getExtendedState()==Frame.MAXIMIZED_BOTH)
setExtendedState(Frame.NORMAL);
}
});
b3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
System.exit(0);
}
});
}
public static void main(String args[])
{
new ButtonAction();
}
}


ButtonAction() : Code for creation of Button and adding ActionListener is written here
new ButtonAction() : Create the object for the class ButtonAction



Spring Hibernate Using GridLayout in AWT Example

GridLayout arranges components in Grid view.

import java.awt.*;
import java.awt.event.*;
class GridLayoutDemo extends Frame
{
List l1,l2;
public GridLayoutDemo()
{
// Set the frame properties
setTitle("GridLayout Demo");
setSize(400,400);
setLayout(new GridLayout());
setLocationRelativeTo(null);
setVisible(true);
// Create lists
l1=new List();
l2=new List();
// Add items to lists
l1.add("Apple");
l1.add("Mango");
l1.add("Orange");
l1.add("Pineapple");
l1.add("Guava");
l1.add("Banana");
l2.add("Potato");
l2.add("Carrot");
l2.add("Onion");
l2.add("Spinach");
l2.add("Radish");
// Add lists
add(l1);
add(l2);
// Add item listeners
l1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
setTitle("Fruit = "+l1.getSelectedItem()+"; Vegetable = "+l2.getSelectedItem());
}
});
l2.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
setTitle("Fruit = "+l1.getSelectedItem()+"; Vegetable = "+l2.getSelectedItem());
}
});
}
public static void main(String args[])
{
new GridLayoutDemo();
}
}


GridLayoutDemo() : Code illustrating GridLayout is written here
new GridLayoutDemo() : Create the object for the class GridLayoutDemo


Spring Hibernate Using FlowLayout in AWT - Example

FlowLayout is one of the Layouts in the AWT. The following program illustrates it.
import java.awt.*;
import java.awt.event.*;
class FlowLayoutDemo extends Frame
{
Button b1,b2,b3;
Label label;
   
    public FlowLayoutDemo()
    {
   
    // Set the frame properties
    setTitle("FlowLayout Demo");
    setSize(400,400);
    setLayout(new FlowLayout());
    setLocationRelativeTo(null);
    setVisible(true);
   
    // Create buttons
    b1=new Button(" Yes");
    b2=new Button("No");
    b3=new Button("Maybe");
   
    // Create label
    label=new Label();
   
    // Add buttons
    add(b1);
    add(b2);
    add(b3);
   
    //  Add label
    add(label);
   
    // Add action listener to buttons
    b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            label.setText("You clicked Yes");
            }
        });
    b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            label.setText("You clicked No");
            }
        });
    b3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            label.setText("You clicked Maybe");
            }
        });
    }
    public static void main(String args[])
    {
    new FlowLayoutDemo();
    }
}
FlowLayoutDemo() : Code illustrating FlowLayout is written here
new FlowLayoutDemo() : Create object for the class FlowLayoutDemo


Spring Hibernate Using the GridBagLayout in AWT

GridBagLayout is quite different and quite similar to FlowLayout, but with a difference in the position.
import java.awt.*;
class GridBagDemo extends Frame
{
Button b1;
Choice c1;
   
    public GridBagDemo()
    {
   
    // Set the frame properties
    setTitle("GridBagLayout Demo");
    setSize(400,400);
    setLayout(new GridBagLayout());
    setLocationRelativeTo(null);
    setVisible(true);
   
    // Create button
    b1=new Button(" Buy");
   
    // Create choice
    c1=new Choice();
   
    // Add items
    c1.add("Apple");
    c1.add("Mango");
    c1.add("Orange");
    c1.add("Guava");
   
    // Add choice
    add(c1);
   
    // Add button
    add(b1);
    }
    public static void main(String args[])
    {
    new GridBagDemo();
    }
}
GridBagDemo() : Code illustrating GridBagLayout is written here
new GridBagDemo() : Create the object for the class GridBagDemo

 

Spring Hibernate Create a panel in AWT : Easy way

Create a panel and attach it to a frame. Here is the code :
import java.awt.*;
class AWTPanel extends Frame
{
Panel panel;
Button b1,b2;
    public AWTPanel()
    {
   
    // Set frame properties
    setTitle("AWT Panel"); // Set the title
    setSize(400,400); // Set size to the frame
    setLayout(new FlowLayout()); // Set the layout
    setVisible(true); // Make the frame visible
    setLocationRelativeTo(null);  // Center the frame
   
    // Create the panel
    panel=new Panel();
   
    // Set panel background
    panel.setBackground(Color.gray);
   
    // Create buttons
    b1=new Button(); // Create a button with default constructor
    b1.setLabel("I am button 1"); // Set the text for button
   
    b2=new Button("Button 2"); // Create a button with sample text
    b2.setBackground(Color.lightGray); // Set the background to the button
   
    // Add the buttons to the panel
    panel.add(b1);
    panel.add(b2);
   
    // Add the panel to the frame
    add(panel);
   
    }
    public static void main(String args[])
    {
    new AWTPanel();
    }
}
AWTPanel() : Code for creation of a panel is written here
new AWTPanel() : Create the object for the class


Spring Hibernate Creating Menus and MenuItems in AWT Example

A menu is attached to a menu bar and a menu item is attached to a menu. Here is the simple way to create a menu along with menu items.
import java.awt.*;
class AWTMenu extends Frame
{
MenuBar mbar;
Menu menu,submenu;
MenuItem m1,m2,m3,m4,m5;

    public AWTMenu()
    {
   
    // Set frame properties
    setTitle("AWT Menu"); // Set the title
    setSize(400,400); // Set size to the frame
    setLayout(new FlowLayout()); // Set the layout
    setVisible(true); // Make the frame visible
    setLocationRelativeTo(null);  // Center the frame

    // Create the menu bar
    mbar=new MenuBar();
   
    // Create the menu
    menu=new Menu("Menu");
   
    // Create the submenu
    submenu=new Menu("Sub Menu");
   
    // Create MenuItems
    m1=new MenuItem("Menu Item 1");
    m2=new MenuItem("Menu Item 2");
    m3=new MenuItem("Menu Item 3");
   
    m4=new MenuItem("Menu Item 4");
    m5=new MenuItem("Menu Item 5");
   
    // Attach menu items to menu
    menu.add(m1);
    menu.add(m2);
    menu.add(m3);
   
    // Attach menu items to submenu
    submenu.add(m4);
    submenu.add(m5);
   
    // Attach submenu to menu
    menu.add(submenu);
   
    // Attach menu to menu bar
    mbar.add(menu);
   
    // Set menu bar to the frame
    setMenuBar(mbar);
    }
    public static void main(String args[])
    {
    new AWTMenu();
    }
}
AWTMenu() : Code for creation of menus is written here
new AWTMenu() : Create the object for the class

Spring Hibernate Creating an AWT Button : Quick steps

Creating an AWT Button the easy way :
import java.awt.*;
class AWTButton extends Frame
{
Button b1,b2;
    public AWTButton()
    {
   
    // Set frame properties
    setTitle("AWT Frame"); // Set the title
    setSize(400,400); // Set size to the frame
    setLayout(new FlowLayout()); // Set the layout
    setVisible(true); // Make the frame visible
    setLocationRelativeTo(null);  // Center the frame
   
    // Create buttons
    b1=new Button(); // Create a button with default constructor
    b1.setLabel("I am button 1"); // Set the text for button
   
    b2=new Button("Button 2"); // Create a button with sample text
    b2.setBackground(Color.lightGray); // Set the background to the button
   
    add(b1);
    add(b2);
    }
    public static void main(String args[])
    {
    new AWTButton();
    }
}
AWTButton() : Code for creation of an AWT Button is written here.
new AWTButton() : Create the object for the class AWTButton

Spring Hibernate Creating an AWT frame - Easy way

Creating a frame in AWT is simple and it can be done in many ways. Yet the most preferred and the most easiest way is here.
import java.awt.*;
class AWTFrame extends Frame
{
    public AWTFrame()
    {
    setTitle("AWT Frame"); // Set the title
    setSize(400,400); // Set size to the frame
    setVisible(true); // Make the frame visible
    setBackground(Color.red); // Set the background
    setExtendedState(MAXIMIZED_BOTH); // Make the frame maximized
    setCursor(Cursor.HAND_CURSOR); // Deprecated
    }
   
    public static void main(String args[])
    {
    new AWTFrame();
    }
}
import java.awt.* : Import everything from java.awt package excluding its sub packages
AWTFrame() : The default constructor of the class AWTFrame
new AWTFrame() : Creating the object for the AWTFrame class

+ Next Creating AWT Button

- Previous AWT Basics

AWT Tutorial Home

Spring Hibernate Using Robot class in Java AWT

Robot Class in Java AWT



Robot class in java.awt package itself, means that it acts like a Robot i.e. press and releases a key, press, release, move mouse and can also create screen capture. The following example, illustrates, how to use robot class to open and write in Notepad and again close it.









Robot Class - Open, Write in, Close Notepad.


import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;

class JavaRobot
{
public static void main(String args[]) throws Exception
{
Robot r=new Robot();

r.setAutoDelay(200);

r.keyPress(KeyEvent.VK_WINDOWS);
r.keyPress(KeyEvent.VK_R);
r.keyRelease(KeyEvent.VK_R);
r.keyRelease(KeyEvent.VK_WINDOWS);

r.keyPress(KeyEvent.VK_N);
r.keyRelease(KeyEvent.VK_N);

r.keyPress(KeyEvent.VK_O);
r.keyRelease(KeyEvent.VK_O);

r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_T);

r.keyPress(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_E);

r.keyPress(KeyEvent.VK_P);
r.keyRelease(KeyEvent.VK_P);

r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);

r.keyPress(KeyEvent.VK_D);
r.keyRelease(KeyEvent.VK_D);

r.keyPress(KeyEvent.VK_ENTER);

r.keyPress(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_H);

r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);

r.keyPress(KeyEvent.VK_I);
r.keyRelease(KeyEvent.VK_I);

r.keyPress(KeyEvent.VK_SPACE);
r.keyRelease(KeyEvent.VK_SPACE);

r.keyPress(KeyEvent.VK_B);
r.keyRelease(KeyEvent.VK_B);

r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);

r.keyPress(KeyEvent.VK_I);
r.keyRelease(KeyEvent.VK_I);


r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_F4);

r.keyRelease(KeyEvent.VK_F4);
r.keyRelease(KeyEvent.VK_ALT);

r.keyPress(KeyEvent.VK_RIGHT);
r.keyRelease(KeyEvent.VK_RIGHT);

r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

}
}

keyPress(): Presses a given key.

keyRelease(): Releases a given key, usually the key that is pressed will be released. Nothing happens, if you call keyRelease() for a key that is not pressed.

setAutoDelay(): Auto wait for some time for every action that the Robot class do. Beneficial because, relieves burden in calling delay() all the time.

KeyEvent: Class in the java.awt.event package, generated when keyboard related operation is done.





Spring Framework Example on AWT FileDialog

This illustrates a small example on the java.awt.FileDialog, the class that does the job of a JFileChooser in Swing i.e. opening and/or saving files. In some cases, we can find that FileDialog is much better than the swing JFileChooser because, JFileChooser lacks the 2 main things, auto complete and the file context menu by default. But still programmers prefer using JFileChooser and they try to crack it to get the features they want. Whatsoever, though FileDialog has got these awesome features, it is platform dependent unlike JFileChooser and is developed using the native C/C++ code. In this example i'll be discussing with an example on FileDialog.


import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

class FileDialogExample extends JFrame

{

JFrame thisFrame;

JComboBox jb;

JButton b;

public FileDialogExample()

{

// Store current object in thisFrame

thisFrame=this;

createAndShowGUI();

}



private void createAndShowGUI()

{



// Set frame properties

setTitle("File Dialog Example");

setSize(500,500);

setLayout(new FlowLayout());

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);



// Create JComboBox

jb=new JComboBox();



// Add items to the frame

jb.addItem("LOAD"); // 0 index

jb.addItem("SAVE"); // 1 index



b=new JButton("Fire!");

b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)

{

// Create a FileDialog whose parent is this frame and with title selected in JComboBox

FileDialog fd=new FileDialog(thisFrame,(String)jb.getSelectedItem());



// Set a dir

fd.setDirectory("E:\\java");



// Set FileDialog.LOAD=0 or FileDialog.SAVE=1

fd.setMode(jb.getSelectedIndex());



// Make it visible

fd.setVisible(true);

}

});



// Add JComboBox

add(jb);



// Add button

add(b);

}



public static void main(String args[])

{

new FileDialogExample();

}

}

Output of the program

Screenshot of FileDialog in AWT


I think everything is understood right from the program itself with the help of comments. This is just a simple example of FileDialog in AWT.

Spring Hibernate Why doesn't AWT Frame close? Ok. Lets close it!

Why doesn't AWT Frame close?


AWT Frame is written using the native code i.e. C/C++ and is not given the functionality to close by default on clicking the close button. There may be several reasons for this, like if we create an application using the Frame class, and some operation is going on and accidentally the user clicked the close button. Then what happens, the application closes and any saved data will be lost unless if we code what to happen when user closes the window. So, it is not provided by default, not only in the AWT but also in the Swing, but in Swing if you can just notice, you will observe the frame disposing but the application doesn't close. The application keeps running in the background. This is what the reason well, i thought of. Any other? Dropping a comment will be appreciated.

How can we close it?


Closing it is dead simple. All you need to know at first, is what action gets fired, when some operation on the Window is opened. It is obvious here, the WindowListener in the java.awt.event package (Ofcourse, all the AWT Event classes reside there). So it is clear i think so, that you will have to implement or write an anonymous inner class or do whatever you want to handle the operations on the AWT frame within your hands. So, in this example i will teach to just terminate (exit) the program when the close button on the Frame is clicked. Other code, ofcourse can be coded upon your need. Thanks, for reading and just look at the example.

The Example



import java.awt.*;
import java.awt.event.*;
class CloseAWTFrame extends Frame
{

Button b1;
public CloseAWTFrame()
{
setTitle("Hi! I am a Frame");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);

// Just add a button (optional)
b1=new Button("I am a button!");
add(b1);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}

public static void main(String args[])
{
new CloseAWTFrame();
}
}


Explanation


WindowAdapter: An adapter class, simply it is an abstract class that implement the WindowListener interface, it's body is not provided and we have to. The use of this is, we need not implement all the abstract methods of the WindowListener interface, instead just a method or two depending upon our need can be implemented.

Why windowClosing(WindowEvent we)? The program has to exit at the time of closing the window i.e. when the user is clicking the button. For example, if you write windowClosed instead of WindowClosing then the window will not be closed because it means to terminate the program after the window is closed and the window will never be closed unless you write it in the windowClosing. 

System.exit(0): Nothing, close the program (i.e. terminate the current running JVM) normally. The 0 says it to terminate normally.

What still? Nothing, yet one more thing, if you just want to dispose the frame instead of terminating the entire program, it is your wish as said earlier, if you, then dispose() method is for you.

Spring Hibernate Using AWT TextArea in Java - Methods and Constructors

Introduction java.awt.TextArea Constructors and Methods


Here is an example of using TextArea in AWT in Java. These examples show you how to create AWT TextAreas using all the constructors and will also introduce some methods of the java.awt.TextArea class that are useful for further implementation.

What is a TextArea?


A Text Area is a GUI component that is used to store multiple rows of text unlike a Text Field.

java.awt.TextArea Constructors


  public TextArea()
  public TextArea(String text)
  public TextArea(int rows, int columns)
  public TextArea(String text, int rows, int columns)
  public TextArea(String text, int rows, int columns, int scrollbars)

All the constructors throw java.awt.HeadlessException.

java.awt.TextArea Methods


Insert text in the textarea at the particular position.
  public void insert(java.lang.String text, int position);
  public synchronized void insertText(java.lang.String text, int position);

Append text in the textarea.
  public void append(java.lang.String text);
  public synchronized void appendText(java.lang.String text);

Replace text between given start and end points with the given text.
  public void replaceRange(java.lang.String text, int start, int end);
  public synchronized void replaceText(java.lang.String text, int start, int end);

Set/Get no.of rows in the TextArea.
  public int getRows();
  public void setRows(int rows);

Set/Get no.of columns in the TextArea.
  public int getColumns();
  public void setColumns(int columns);

Get the Scrollbar constant value for a textarea. See down for Scrollbar constants.
  public int getScrollbarVisibility();

Set/Get Text in the TextArea. If text exists, then the text in it will be replaced with the given text.
  public void setText(String text);
  public String getText();

java.awt.TextArea Constants


Scrollbars Constants
  public static final int SCROLLBARS_BOTH; (Value 0)
  public static final int SCROLLBARS_VERTICAL_ONLY; (Value 1)
  public static final int SCROLLBARS_HORIZONTAL_ONLY; (Value 2)
  public static final int SCROLLBARS_NONE; (Value 3)

The Example
import java.awt.*;
class JavaAWTTextArea extends Frame
{

TextArea ta,ta1,ta2,ta3,ta4;

public JavaAWTTextArea()
{

setTitle("AWT TextArea Demo");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
// Create textarea using first constructor
ta=new TextArea();

// Create textarea using second constructor
ta1=new TextArea("Java-Demos.blogspot.com");

// Create textarea using third constructor
ta2=new TextArea(10,25);

// Create textarea using fourth constructor
ta3=new TextArea("Java-Demos.blogspot.com",10,25);

// Create textarea using fifth constructor
ta4=new TextArea("Java-Demos.blogspot.com",10,25,TextArea.SCROLLBARS_HORIZONTAL_ONLY);

// Using methods
ta.setText("Java-Demos.blogspot.com");

        // Non synchronized method
ta1.append("I am appended.");
// Synchronized method
ta2.appendText("I am appended.");

// Synchronized method
ta3.insertText("Java-Demos.blogspot.com",4);

// Non Synchronized method
ta4.insert("Java-Demos.blogspot.com",5);

// Set no. of rows
ta.setRows(10);
// Get no.of rows
System.out.println("No.of rows of ta "+ta.getRows());

// Set no.of columns
ta.setColumns(10);

// Get no.of columns
System.out.println("No. of cols for ta "+ta.getColumns());

// Get Scrollbar Visibilty
System.out.println("Scrollbar for ta4 "+ta4.getScrollbarVisibility());
// Replace text (Synchronized)
ta1.replaceText("Java-Demos.blogspot.com",23,37);

// Replace text (Non Synchronized)
ta1.replaceRange("Java-Demos.blogspot.com",23,37);

// Add textareas
add(ta);
add(ta1);
add(ta2);
add(ta3);
add(ta4);
}
public static void main(String args[])
{
new JavaAWTTextArea();
}
}

-------------------------------------
Output
-------------------------------------

No.of rows of ta 10
No. of cols for ta 10
Scrollbar for ta4 2





Spring Framework Get Data from Clipboard in Java

An example on getting and printing a string from system clipboard in Java in just 2 statements.


Example




import java.awt.*;

import java.awt.datatransfer.*;

class SystemClipboard

{

public static void main(String args[]) throws Exception

{



// Create a Clipboard object using getSystemClipboard() method

Clipboard c=Toolkit.getDefaultToolkit().getSystemClipboard();



// Get data stored in the clipboard that is in the form of a string (text)

System.out.println(c.getData(DataFlavor.stringFlavor));



}

}

Explanation


java.awt.*: Contains Toolkit class.

java.awt.datatransfer.*: Contains Clipboard class.

Exception: UnsupportedFlavorException is thrown.

Flavor: Nothing but the type of the data. We need to specify it in order to get what type of data we want. For example, if clipboard contains an image, then it is imageFlavor or if it contains only characters then stringFlavor. These are constants however present in the java.awt.datatransfer.DataFlavor class.

Toolkit.getDefaultToolkit().getSystemClipboard(): Toolkit class has a public static method getDefaultToolkit() which returns an instance of the java.awt.Toolkit class which is useful for calling the normal public method getSystemClipboard(). This method returns the java.awt.datatransfer.Clipboard object which will further be used to get data from the system clipboard.

c.getData(DataFlavor.stringFlavor): Get the data in the clipboard that is just in the form of general characters. An exception is thrown if either the clipboard is empty or contains other than string (for example an image).


Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()