AWT中paint(Graphics)方法参数传入问题及相关绘制疑问
Hey there! Let's work through your AWT GUI questions—this stuff can feel a bit opaque at first, but it'll make sense once we break it down.
paint() Method and Its Graphics Parameter First off, you're right that you almost never need to explicitly call paint() yourself. Here's why:
- AWT's Event Dispatch Thread (EDT) handles calling
paint()automatically whenever your component needs to be drawn or refreshed. That includes when the window first opens, when it's resized, when it's uncovered after being hidden by another window, or when you callrepaint()(more on that in a sec).
Now, about the Graphics parameter:
- Think of this object as your drawing toolkit provided by the AWT framework. It encapsulates everything you need to draw on the component: access to the component's drawing surface, tools to set colors/fonts, and all the drawing methods like
drawRect(),drawOval(), etc. - When the EDT calls
paint(), it passes this pre-configuredGraphicsinstance to you—your job is to use it to render whatever content you want on the component.
Here's a quick example to make this concrete:
import java.awt.Canvas; import java.awt.Graphics; import java.awt.Color; public class MyDrawingCanvas extends Canvas { @Override public void paint(Graphics g) { // Always call super.paint(g) first to clear old content and set up defaults super.paint(g); // Use the Graphics object to set a color and draw a rectangle g.setColor(Color.BLUE); g.drawRect(20, 20, 150, 100); } }
If you ever need to force a refresh of your component (like after updating some data that changes the drawing), call repaint() instead of paint(). repaint() tells the EDT to schedule a paint() call, which is the safe, thread-correct way to trigger redraws.
drawRect()? Absolutely! The drawRect(int x, int y, int width, int height) method accepts any valid integer values—whether they're hard-coded constants or the result of mathematical calculations.
For example, if you want to draw a rectangle centered in your component, you can calculate the position based on the component's current size:
@Override public void paint(Graphics g) { super.paint(g); // Calculate centered position and size int canvasWidth = getWidth(); int canvasHeight = getHeight(); int rectWidth = 100; int rectHeight = 100; int startX = (canvasWidth - rectWidth) / 2; int startY = (canvasHeight - rectHeight) / 2; // Draw the centered rectangle g.drawRect(startX, startY, rectWidth, rectHeight); }
You can even use more complex calculations—like using Math class methods, variables from your program, or user input. Just make sure the final result is an int (if you're working with floating-point numbers, you'll need to cast them to int, e.g., (int)(Math.random() * 200)).
内容的提问来源于stack exchange,提问作者user9637278

