Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 330


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Java: javax.swing.Timer

Go to all tips in Java Notes by Fred Swartz

A javax.swing.Timer object calls an action listener at regular intervals or only once. For example, it can be used to show frames of an animation many times per second, repaint a clock every second, or check a server every hour.

Java 2 added another class by the same name, but in the java.util package, java.util.Timer, which is better for large timing tasks. It also has more features (eg, it can start at a given time, use either a fixed delay or fixed rate), but javax.swing.Timer is easier to use for simple animations. It is also advisable to use java.util.Timer for headless programs, those without a GUI. To prevent ambiguous references, always write the fully qualified name.

To Use a Timer

  1. import java.awt.event.*; // for ActionListener and ActionEvent
  2. Create a Timer object, giving a time interval in milliseconds, and an action listener. This would usually be done once in a constructor. The prototype usage is:
        javax.swing.Timer yourTimer = 
               new javax.swing.Timer(int milliseconds, ActionListener doIt);
    The following example creates a Timer that calls an anonymous action listener to repaint a panel every second (1000 milliseconds).
    javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  p.repaint();
              }
           });
  3. Start the timer by calling the timer's start method. For example,
    t.start();

To Stop a Timer

Call the timer's stop method. Example,

t.stop();

See the discussion below to see when it's important to stop a timer in an applet.

Fixed interval versus fixed rate

javax.swing.Timer uses a fixed delay, which means that the time from the return from an action listener to the time of the next call is a fixed time. Therefore the interval between calls will be longer because of the time used by the action listener and overhead operations such as garbage collection. This is ok for many animations, but not where exact timing is required. The clock animation examples show this deficiency, as you may notice when the clock "skips" a second every so often to catch up to the real time. The java.util.Timer class provides a fixed rate option which would be a better way to run a clock, but I haven't made the time to update the examples.

Starting and Stopping Animation in an Applet

Because animation uses computer resources (CPU time and memory), the browse rmay ask the applet to stop what it is doing (by calling the applet's stop method) when the applet is no longer visible, eg, the browser moves to a different page or minimizes the page. It calls the applet's start method when it wants the applet to become active again. Applets usually don't need stop and start methods, but if your applet is using a Timer to display animation or is playing sound, provide these methods.

Writing start and stop methods for Applets

Starting and stopping a timer is very simple. For example, just add the following lines to your applet (assuming t is a Timer):

public void start() {t.start();}
public void stop()  {t.stop();}

Additional Timer methods

t.setRepeats(boolean flag);
t.setInitialDelay(int initialDelay);
if (t.isRunning()) ...

And others.

Examples of Timer



45 comments | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Tuesday, March 29, 2005 (00:00:00) (6546 reads)

Java Lesson 39: An introduction to GridBagLayout

Go to all tips in Java Lessons by Jon Huhtala
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 39 by Jon Huhtala

An introduction to GridBagLayout


Overview

GridBagLayout arranges components in a flexible grid pattern that permits larger components to span multiple rows and columns. It is a powerful layout manager, but difficult to master. Fortunately, only a superficial knowledge of GridBagLayout is required for Java certification.

GridBagLayout

  • May be used in any GUI application (in applets and in windows programs).

  • Is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic rectangular grid of cells, with each component occupying one or more cells, called its display area.

For example, a flexible grid of 4 rows and 4 columns can be made to appear as follows

1

2

3

4

5

6

where component 1 covers the first cell of rows one through three, component 2 covers the last three cells of row one, component 3 occupies the middle cells of rows two and three, components 4 and 5 cover the last cell of rows two and three respectively, and component 6 spans all four cells of row four.

  • Has a single constructor that requires no parameters. For example, to set the layout manager of the current container to GridBagLayout one need only code:

setLayout(new GridBagLayout());

  • Depends upon a GridBagConstraints object to determine where a component will be placed within the container and how the component will appear within its display area. The GridBagConstraints class will be covered shortly.

  • Has a number of methods that are not needed for routine programming work.


The GridBagConstraints class

  • Specifies constraints (settings) for components that are laid out using the GridBagLayout class

  • In most cases, a single GridBagConstraints object can be instantiated and its settings modified prior to adding each component. For example,

GridBagConstraints c = new GridBagConstraints();

creates a GridBagConstraints object having default settings. If someObject is an object to be added to the container, the general technique for adding it is to

  1. Modify one or more public instance variables of object c

  2. Add someObject to the container by coding

add(someObject, c);

  1. Repeat steps 1 and 2 for the next component.

  • Contains a number of public variables and constants. The following are most useful:

gridx and gridy

Used to specify the cell address of the top-left corner of the component within the grid. The address of the top-left corner of the container is gridx = 0 and gridy = 0. Use GridBagConstraints.RELATIVE (the default value) to specify that the component be placed just to the right of (for gridx) or just below (for gridy) the previous component that was added to the container.

gridwidth and gridheight

Used to specify the number of cells in a row (for gridwidth) or column (for gridheight) in the component's display area. The default value is 1. Use GridBagConstraints.REMAINDER to specify that the component be the last one in its row (for gridwidth) or column (for gridheight). Use GridBagConstraints.RELATIVE to specify that the component be the next to last one in its row (for gridwidth) or column (for gridheight).

fill

Used when the component's display area is larger than the component's requested size to determine whether (and how) to resize the component. Possible values are GridBagConstraints.NONE (the default), GridBagConstraints.HORIZONTAL (make the component wide enough to fill its display area horizontally, but don't change its height), GridBagConstraints.VERTICAL (make the component tall enough to fill its display area vertically, but don't change its width), and GridBagConstraints.BOTH (make the component fill its display area entirely).

anchor

Used when the component is smaller than its display area to determine where (within the display area) to place the component. Valid values are GridBagConstraints.CENTER (the default), GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagConstraints.EAST, GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHWEST, GridBagConstraints.WEST, and GridBagConstraints.NORTHWEST.

weightx and weighty

Used to determine how to distribute space, which is important for specifying resizing behavior. Unless you specify a weight for at least one component in a row (weightx) and column (weighty), all the components clump together in the center of their container. This is because when the weight is zero (the default), the GridBagLayout object puts any extra space between its grid of cells and the edges of the container.

Other variables exist to control a component's internal padding and insets (the space that surrounds a component within its display area). Consult the Java API for more details.

A sample applet that uses GridBagLayout

The following applet demonstrates how GridBagLayout can be used manage components of various sizes:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class App extends Applet {

// Object references and variables to support "card" processing.

Panel cards;
CardLayout myCardLayout;
int cardIndex;

// Object references for user controls.

Button next;
Button previous;
Choice pickOne;

// Applet initialization.

public void init() {
resize(500, 350);
setBackground(Color.lightGray);

// Choose GridBagLayout and create a GridBagConstraints object
// for use in laying out components to be added to the container.

setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

// Initialize constraints to stretch small components to fill
// their entire display area, give all rows equal height when
// distributing extra vertical space, and give all columns equal
// width when distributing extra horizontal space.

c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.weightx = 1;

// Build the "Card in View" label and add it to the top-left
// cell in the layout.

Label hdg = new Label("Card in view");
hdg.setAlignment(Label.CENTER);
hdg.setFont(new Font("SanSerif", Font.BOLD, 14));
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
add(hdg, c);

// Build the choice menu and add it to the right-most 2 cells
// of the first row of the layout.

pickOne = new Choice();
pickOne.addItem("Card 1");
pickOne.addItem("Card 2");
pickOne.addItem("Card 3");
pickOne.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {

// Display the selected "card" within the container and
// update the current card index being displayed.

myCardLayout.show(cards, pickOne.getSelectedItem());
cardIndex = pickOne.getSelectedIndex();
}
}
);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 1;
add(pickOne, c);

// Create the "Next" button and add it to the left-most cell
// in the second row of the layout.

next = new Button(">");
next.setFont(new Font("SanSerif", Font.BOLD, 1Cool);
next.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {

// Display the next "card" in the container and make
// it the current selection in the Choice component

myCardLayout.next(cards);
if (cardIndex < cards.getComponentCount() - 1) {
cardIndex++;
}
else {
cardIndex = 0;
}
pickOne.select(cardIndex);
}
}
);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
add(next, c);

// Instantiate objects and variables to support "card" processing.

cards = new Panel();
myCardLayout = new CardLayout();
cardIndex = 0;

// Build the container of "cards" and add it to the right-most two
// cells of rows 2 and 3 in the layout. It is a large component.

cards.setLayout(myCardLayout);
Label x = new Label("Hello World!");
x.setBackground(Color.black);
x.setForeground(Color.white);
x.setFont(new Font("Serif", Font.PLAIN, 36));
x.setAlignment(Label.CENTER);
cards.add(x, "Card 1");
Label y = new Label("Java is Fun!");
y.setBackground(Color.white);
y.setForeground(Color.black);
y.setFont(new Font("Serif", Font.PLAIN, 36));
y.setAlignment(Label.CENTER);
cards.add(y, "Card 2");
Label z = new Label("Ferris State University");
z.setBackground(Color.red);
z.setForeground(Color.yellow);
z.setFont(new Font("Serif", Font.PLAIN + Font.BOLD, 36));
z.setAlignment(Label.CENTER);
cards.add(z, "Card 3");
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 2;
add(cards, c);

// Create the "Previous" button and add it to the left-most cell
// in the third row of the layout.

previous = new Button("<");
previous.setFont(new Font("SanSerif", Font.BOLD, 1Cool);
previous.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {

// Display the previous "card" in the container and make
// it the current selection in the Choice component

myCardLayout.previous(cards);
if (cardIndex > 0) {
cardIndex--;
}
else {
cardIndex = cards.getComponentCount() - 1;
}
pickOne.select(cardIndex);
}
}
);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(previous, c);
}
}

Notes:

  1. Each component is placed in the container based upon its absolute cell position. This is done via the gridx and gridy variables of the GridBagConstraints object.

  2. The cell width and cell height of each component is specified via the gridwidth and gridheight variables of the GridBagConstraints object.

A sample windows program that uses GridBagLayout

The following windows program demonstrates how components can extend over multiple columns when using a GridBagLayout to manage the container:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements ActionListener {

// Object references.

Button b1, b2, b3, b4, b5, b6, b7;
Label msg;

// Processing starts here.

public static void main(String[] args) {
App myWindow = new App("GridBagLayout");
myWindow.setSize(300, 300);
myWindow.setVisible(true);
}

// Class constructor.

public App(String title) {
super(title);
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);

setFont(new Font("SanSerif", Font.BOLD, 16));

// Choose GridBagLayout and create a GridBagConstraints object
// for use in laying out components to be added to the container.

setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

// Initialize constraints to stretch small components to fill
// their entire display area, give all rows equal height when
// distributing extra vertical space, and give all columns equal
// width when distributing extra horizontal space.

c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.weightx = 1;

// Build the first row of components.

b1 = new Button("1");
b1.addActionListener(this);
add(b1, c);
b2 = new Button("2");
b2.addActionListener(this);
add(b2, c);
b3 = new Button("3");
b3.addActionListener(this);
c.gridwidth = GridBagConstraints.REMAINDER; // Last on row.
add(b3, c);

// Don't let subsequent rows determine how to allocate extra
// horizontal space.

c.weightx = 0;

// Reset the grid width to one cell before building a new row.

c.gridwidth = 1;

// Build the second row of components.

b4 = new Button("4");
b4.addActionListener(this);
add(b4, c);
msg = new Label("Click one");
msg.setAlignment(Label.CENTER);
c.gridwidth = GridBagConstraints.REMAINDER; // Last on row.
add(msg, c);

// Reset the grid width to one cell before building a new row.

c.gridwidth = 1;

// Build the third row of components.

b5 = new Button("5");
b5.addActionListener(this);
c.gridwidth = GridBagConstraints.RELATIVE; // Next to last on row.
add(b5, c);
b6 = new Button("6");
b6.addActionListener(this);
c.gridwidth = GridBagConstraints.REMAINDER; // Last on row.
add(b6, c);

// Reset the grid width to one cell before building a new row.

c.gridwidth = 1;

// Build the fourth row of components.

b7 = new Button("7");
b7.addActionListener(this);
c.gridwidth = GridBagConstraints.REMAINDER; // Last on row.
add(b7, c);
}

// Required method of the ActionListener interface.

public void actionPerformed(ActionEvent e) {
msg.setText("You clicked " + ((Button)e.getSource()).getLabel());
}
}

Notes:

  1. Each component is placed in its row based upon its relative column position. The next to the last component is specified via the GridBagConstraints.RELATIVE constant and the last component specified via the GridBagConstraints.REMAINDER constant in conjunction with the gridx variable of the GridBagConstraints object.

  2. In this sample, all components have equal height.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. If c is a GridBagConstraints object, which one of the following specifies that the top-left corner of the next component is to be placed in the second column of the first row of a container using GridBagLayout?

  1. c.gridx = 2;
    c.gridy = 1;

  1. c.gridx = 1;
    c.gridy = 0;

  2. c.gridx(2);
    c.gridy(1);

  3. c.gridx(1);
    c.gridy(0);

  4. c.setX(1);
    c.setY(0);

  1. If c is a GridBagConstraints object, which one of the following specifies that the next component is to be the last one in its column of a container using GridBagLayout?

  1. c.gridheight = GridBagConstraints.REMAINDER;

  1. c.gridwidth = GridBagConstraints.REMAINDER;

  2. c.gridheight(GridBagConstraints.RELATIVE);

  3. c.gridwidth(GridBagConstraints.RELATIVE);

  4. c.gridheight = GridBagConstraints.RELATIVE;

  1. Assume that someComponent is the object reference of a component and c is the object reference of a properly set GridBagConstraints object. If the current container is using GridBagLayout, which one of the following will place someComponent in the container?

    1. place(c, someComponent);

    1. place(someComponent, c);

    2. add(c, someComponent);

    3. add(someComponent, c);

    4. c.add(someComponent, this);

  1. Assume that c is the object reference of a GridBagConstraints object. Which one of the following specifies that a component too small to fill its display area will be positioned in the bottom-right corner of its display area?

  1. c.anchor(GridBagConstraints.SOUTHWEST);

  2. c.anchor = GridBagConstraints.SOUTHWEST;

  3. c.anchor(GridBagConstraints.SOUTHEAST);

  4. c.anchor = GridBagConstraints.SOUTHEAST;

  5. c.anchor(GridBagConstraints.SOUTH + GridBagConstraints.EAST);


25461 bytes more | 7 comments | Printer Friendly Page  Send to a Friend | Score: 5
Posted by jalex on Monday, March 28, 2005 (00:00:00) (9871 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331|
330
| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy