Friday, July 19, 2013

Frame

In Java, Frame is a class (in awt package) that can be used to create a top-level window in a graphical user interface program. The window that is the instance of the Frame class can have title, border, and menu bar. This contrasts to a window created by the Applet class.

Frame constructors:
-Frame()
-Frame(String title)

Its useful methods:
-add(Component c)
-setExtendedState(int state)
-setLocation(int x,int y)
-setResizable(boolean resizable)
-setSize(int width,int height)
-setSize(Dimension ds)
-setTitle(String title)
-setVisible(boolean visible)

Example:

import java.awt.Frame;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class WindowShow extends Frame{
WindowShow(){
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(400,300); //set window size
setTitle("Form"); //set window title
setVisible(true); //make sure the window is visible
Image iconimage=Toolkit.getDefaultToolkit().getImage("d:/myprogram/file-mover.png");
setIconImage(iconimage);//set the icon of window to an image
setLocation(300,300); //display the window at point (300,300)

//let the window close when its close-icon is clicked
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AwtTest {
public static void main(String[] args){
new WindowShow();

}
}
Frame in Java

2 comments:

  1. If i want to maximize the frame window when the program firstly loads, can i use the setSize(int w,int h)? If you have a good solution please suggest.

    ReplyDelete
  2. You can use the setSize(int w,int h) to maximize the frame to fit the screen. To get the screen size, use getScreenSize() method of the toolkit class. The returned dimension object contains the width and height of the screen that will be supplied to the setSize method.
    Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
    int w=(int)ds.getWidth();
    int h=(int)ds.getHeight();
    setSize(w,h);

    or

    setSize(ds);

    The easy code to maximize the frame i always use is shown below.
    setExtendedState(Frame.MAXIMIZED_BOTH);

    ReplyDelete