devxlogo

Canvas in a ScrollPane

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 thecenter will expand along both the vertical and horizontal axes. When you added your canvas to the frame, if you did not specify the regionwhere 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 layoutmanager 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 differentlayout 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);  }}
See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist