Tutorial: JFrame and JPanel

Posted: February 13, 2011 in Java, Uncategorized

JFrame represents a framed window and a
JPanel represents some area in which controls (e.g., buttons, checkboxes, and textfields) and visuals (e.g., figures, pictures, and even text) can appear. Windows can contain/display multiple panels, although in the simplest GUIs, we will associate just one panel with a window.

Swing is a collection of related classes for writing stand-alone Java applications: applets are written using other Java packages.
By extending JFrame, the View subclass inherits hundreds of methods from not only JFrame, but its superclasses: the JFrame class is in a hierarchy whose superclasses include (going upward) Frame, Window, Container, Component, and finally Object).
At the top of this heirarchy is the Component class, which is abstract; objects from its concrete subclasses are displayable on the screen, and have the following important methods (along with many many more): isVisible/setVisible (with a boolean parameter), getSize/setSize (with either a Dimension or two int parameters), getLocation/setLocation (with either a Point or two int parameters), and repaint (parameterless).
The Container class is itself considered a Component, but one that in addition collects together other Components, using a LayoutManager to organize them visually; it takes the role of a composite pattern: when we perform an operation on a Container, it performs that operation on all its Components.
The Window class represents a raw window (e.g., no border) with its own internal coordinate system: (0,0) is the windows upper-left hand corner.
The Frame class represents a window with Border and title area (we can specify various kinds of borders and set its associated icon/title).
Finally, the JFrame class represents a Java compatible window: it has an associated content pane, which shows its visual contents.
origin=upper left corner…… bottom right hand corner= (1280,1024) pixels
JFrame methods

*getLocation which returns a Point object

*getSize which returns a Dimension object

*setLocation and setSize methods, which use objects from these classes as parameters

JFrame headers

*icon(setIconImage)

*title(setTitle)

*window control(min,max,close)
To read an icon from a file and put it into the header first requires calling the getImage method in the Toolkit class, passing its result to the setIconImage

method.Toolkit tk        = Toolkit.getDefaultToolkit();

Image   titleIcon = tk.getImage(gifFileName);

setIconImage(titleIcon);
Finally, the method setVisible (with a boolean parameter) determines whether a JFrame appears on (or disappears from) the screen.

============Adapters==========

An adapter is a kind of pattern. Typically, it is a concrete class with a variety of stub methods (typically void methods that immediately return) that can be overriden.
WindowAdapte class

*WindowActivated

*WindowClosed*

WindowDeactivated

*WindowClosing

*WindowIconified

*WindowDeiconified

*WindowOpened.

In the WindowAdapter class, these methods just return immediately, without doing anything (but these methods exist, and are called when the user clicks a window control button).
The JFrame class inherits (from the Window class) the addWindowListener method from the Window superclass. It “listens” for certain components being clicked and call the appropriate method for each component.
addWindowListener(new WindowAdapter());
Of course, because every method in this class does nothing, we have added no new interesting behavior to the JFrame with this method call. But now, let’s define some interesting behavior when the window is closed. We can define the following class.
public class Terminator extends WindowAdapter {

public void windowClosing(WindowEvent e)    {      System.out.println(“Window closing selected: terminating program”);      System.exit(0);

}

}

Java supplies a default constructor for the Terminator class. This class inherits all the stub methods from the WindowAdapter superclass, but it overrides the windowClosing method (the code inside says that when the user clicks the terminate button on this window, print a message, and the entire program itself that created the window should terminate).
Given this class, we can write

addWindowListener(new Terminator());

to give the JFrame the new behavior that we want.
OR we can use the Terminator(sub class) of WindowAdapter(super class) without even mentioning it.
addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)    {      System.out.println(“Window closing selected: terminating program”);      System.exit(0);

}

}
=================The JPanel Class=============
Once we write a JFrame for our GUI, we often add one or more objects to it, each from a subclass extending JPanel. Typically, each sublcass will define some instance variables and a constructor (to initialize them), and overrides the inherited paintComponent method with one that is special to the subclass. The paintComponent method determines what figures, images, and/or text (controls like buttons and textfields are painted automatically) appear on the part of the screen that is owned by the JPanel.
To override the inherited paintComponent method, we must write a void method with one parameter: a reference to an object of type Graphics (called the Graphics context: see the next section for a short discussion of this class), which contains all the methods for drawing figures, images, and text.
The Java runtime system automatically calls this paintComponent method whenever the size of its JFrame is changed, whenever other windows are moved to uncover part of the JFrame, and whenever the JFrame is deiconified after being iconified (subclasses of the WindowAdapter can add special behavior for such events as well).
In all cases, the paintComponent method is called to redisplay the contents of the JPanel, now that the amount of it that is visible has been “changed”.
If we want to call the paintComponent method we must do so by calling a void repaint method.
The screen does not store any information. So whatever we see on the window is whatever is present. If the window is for example maximized then the paintComponent method is called again to display full image.
========JPanel, paintComponent, and the Graphics Context========
Whenever the paintComponent method of a JPanel is called (whether by the Java system or the program itself), it is supplied with a reference to an object from the Graphics class (called its graphics context). The graphics context stores state, including where on the screen the upper-left hand corner of the JPanel is, what is the current color for drawing/text, etc. It does not store anything drawn in the JPanel. The paintComponent method general uses methods from the Graphics class to draw lines, rectangles, ovals, images, and text. In the process, it can change some of these states.
===================Drawing Figures==============


First of all, whenever we specify coordinates, the graphics context will translate them so that (0,0) is the upper-left hand corner of the JPanel. Parts of drawings may go beyond the screen. This is not an error: such parts just won’t be seen.
void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

void drawLine(int x1, int y1, int x2, int y2)

void drawOval(int x, int y, int width, int height)
void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

void drawPolygon(Polygon p)

void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

void drawRect(int x, int y, int width, int height)

void drawRoundRect(int x, int y, int width, int height,  int arcWidth, int arcHeight)
*Line are straight lines

*ovals are drawn with the specified major and minor axes (circles have these axes the same)

*a polygon is specified either by two parallel arrays of matching x and y coordinates, or a Polygon object (see Javadoc) which stores such arrays internally (and can determine whether a point is in a polygon)

*a polyline is like a polygon, but its last point is not connected to its first

*rectangles come in two flavors: square corners and rounded corners (squares just have their width and height the same.

=====================Drawing Images===============
Here are prototypes for the simplest image methods in the Graphics class.

boolean drawImage(Image img, int x, int y, ImageObserver observer)

boolean drawImage(Image img, int x, int y,  int width, int height, ImageObserver observer)

The x and y values specify the upper-left hand of the image. The first method renders the image in it actual size; the second shrinks or expands it to the dimensions width and height.
=====================Drawing Text===============


Objects in the Font class are constructed, specified by a font name (e.g., SanSerif), style (e.g., plain, bold, italic), and size (e.g., 12 point: specified in points, which is 1/72 of an inch). Objects in the FontMetrics class describe a font, with lots of interesting information: the height and width of characters in the font, ascent and descent, etc.
Here are prototypes for the simplest text methods in the Graphics class.
void drawString(String str, int x, int y)

Font getFont()

FontMetrics getFontMetrics()

FontMetrics getFontMetrics(Font f)

void setFont(Font font)
Note: the x and y values specify the baseline of the the text, not its upper-left hand (the baseline is the bottom of the character, not including the descender). The first method renders the text (using the current font and color) starting at the specified coordinate. Before this statement we might write the following code to specify the font to use and get its metrics.  Font        f1  = new Font(“SansSerif”, Font.BOLD, 14);  FontMetrics f1m = g.getFontMetrics(f1);  g.setFont(f1);  g.setColor(Color.blue);With any FontMetrics object we can call the stringWidth method with any String: it returns the width of that String using that Font
===============Buttons==================


Standard buttons are constructed from the JButton class (in the javax.swing package). As with other controls, they inherit hundreds of methods. The typical constructor specifies a String to use as a label for the button (or we can call setLabel with any String later). We can also call inherited methods such as setFont, setBackground, and setForeground, although most standard buttons use default values for these. We can also call the setEnabled method (with a boolean parameter) to tell Java whether a button is pressable (if not, its label will appear as a faded color).
Here is an example of declaring a JButton and performing many of these operations.
JButton b = new JButton(“Cold”);

b.setFont(new Font(“Monospaced”,Font.BOLD,12));

b.setBackground(Color.yellow);

b.setForeground(Color.blue);

Finally, we can use the add method to add any kind of Component to a JPanel.

This is a stripped version of a tutorial on JFrames and JPanels. To read the complete tutorial visit

http://www.cs.cmu.edu/~pattis/15-1XX/15-200/lectures/view/lecture.html

Advertisements
Comments
  1. Daniel says:

    You need to call
    System.exit(0);

    You may add an action listener like this:
    win.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent evt) {
    System.exit(0);
    }
    });

    A complete tutorial on this is available here:

    http://geekroom.de/entwicklung/how-to-java-dem-schliesen-button-das-schliesen-beibringen/

  2. So, instead of coffee in the mug just drink beer something of that nature stronger.
    Having a relative as a tattoo is definitely utilized by many people
    to immortalize a deceased family member. To
    see a greater portion of Stewie along with the other Family you can watch full episodes at View Family Guy Online.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s