Home > Java > javaTutorial > How to Properly Center a Rectangle within a Non-resizable Java Frame?

How to Properly Center a Rectangle within a Non-resizable Java Frame?

Linda Hamilton
Release: 2024-12-05 04:51:14
Original
883 people have browsed it

How to Properly Center a Rectangle within a Non-resizable Java Frame?

How to Center a Rectangle in a Java Frame

Problem:

In Java, you have created a rectangular frame with a fixed size of (800, 400) and set it as non-resizable. The rectangle, drawn with coordinates (50, 50, 700, 300), appears slightly off-center toward the top of the frame.

Answer:

The issue lies in the fact that frames have inherent decorations (border and title bar) that consume space within the frame area. When painting directly to a frame's surface, as assumed in this case, these decorations can shift the perceived center of the frame.

To paint the rectangle in the true center of the frame, you should render it onto the frame's content area. This area excludes the decorations and represents the available surface for painting.

Demonstration:

In the provided Java code example:

  • BadFrame: This frame overrides the paint() method and draws the rectangle directly to the frame itself. It exhibits the off-center problem.
  • PaintablePane: A sub-container that serves as the content area for the goodFrame. It overrides the getPreferredSize() and paintComponent() methods to set the content area's size and draw the rectangle correctly.

The goodFrame then uses the PaintablePane as its content pane, ensuring that all painting occurs within the designated area. The frame's decorations are now considered external to the painting area, and the rectangle is centered as intended.

The above is the detailed content of How to Properly Center a Rectangle within a Non-resizable Java Frame?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template