Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: AWT
Expertise: Beginner
Oct 2, 1998

Canvas in a ScrollPane

Question:
How can you make a canvas nonresizable? The canvas automatically resizes when the frame is resized.

Answer:
The default layout manager for java.awt.Frame is BorderLayout. BorderLayout will expand the components of its associated container along the regions to which they are attached. For example, a component added to the west or east sides will expand along the vertical axis, but not alter its width. A component added to the north or south sides will expand along the horizontal axis, but not alter its height. A component added to the center will expand along both the vertical and horizontal axes. When you added your canvas to the frame, if you did not specify the region where it was to be placed, then it was placed in the center by default.

To eliminate all resizing behavior, you must choose a different layout manager for your container: in this case, a Frame. Which layout manager you choose will depend on exactly where you want the canvas placed. The following example uses FlowLayout to prevent a canvas from being resized after it is placed in a Frame. The canvas remains centered horizontally, but winds up being stuck on the top end of the Frame. If you do not desire this behavior, you will likely have to place the Canvas in a Panel that uses a different layout manager, and then place the Panel in a Frame.

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

public final class FixedCanvas {
  public static void main(String[] args) {
    Canvas canvas;
    Frame frame;
    WindowListener exitListener;

    exitListener = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
	Window window = e.getWindow();
	window.setVisible(false);
	window.dispose();
	System.exit(0);
      }
    };

    canvas = new Canvas();
    canvas.setSize(100, 100);
    canvas.setBackground(Color.white);

    frame = new Frame();
    frame.setBackground(Color.black);
    frame.setLayout(new FlowLayout(FlowLayout.CENTER));
    frame.add(canvas);
    frame.addWindowListener(exitListener);
    frame.pack();
    frame.setVisible(true);
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date