如何为绘制的图形命名?能否为paint方法中绘制的矩形命名以作后续引用?
Great question! The short answer is: you can’t directly "name" the rectangle drawn by g.drawRect(int,int,int,int) because that method only renders pixels to the screen—it doesn’t create a persistent object you can reference later.
But don’t worry, there’s a straightforward workaround: create a Rectangle object (from the java.awt package) that represents your shape, store it as a field in your component, then use that object to draw the rectangle and reference it elsewhere in your code.
Here’s how to adjust your code:
Step 1: Declare a Rectangle field in your class
First, add a class-level field to hold your named rectangle:
import java.awt.Rectangle; // ... other necessary imports (like JPanel, Graphics, etc.) public class YourCustomComponent extends JPanel { // Declare your named rectangle here—this is your referenceable object private Rectangle myNamedRectangle = new Rectangle(10, 10, 50, 30); // x, y, width, height // ... rest of your class code (constructors, methods, etc.) }
Step 2: Draw using the Rectangle object in paint()
Instead of calling g.drawRect directly, use your stored Rectangle object to render the shape. This keeps your drawing tied to the referenceable object:
@Override public void paint(Graphics g) { super.paint(g); // Always call super.paint first to ensure proper component rendering // Option 1: Use the rectangle's properties with drawRect g.drawRect(myNamedRectangle.x, myNamedRectangle.y, myNamedRectangle.width, myNamedRectangle.height); // Option 2 (cleaner): Cast to Graphics2D and use the draw(Rectangle) method Graphics2D g2d = (Graphics2D) g; g2d.draw(myNamedRectangle); }
Step 3: Reference the rectangle later in your code
Now you can use myNamedRectangle anywhere else in your class to modify, check, or interact with the rectangle:
// Example: Move the rectangle 15 pixels down public void shiftRectangleDown() { myNamedRectangle.y += 15; repaint(); // Trigger a repaint to show the updated position } // Example: Check if a mouse click falls inside the rectangle public boolean isClickInsideRectangle(int mouseX, int mouseY) { return myNamedRectangle.contains(mouseX, mouseY); } // Example: Resize the rectangle public void resizeRectangle(int newWidth, int newHeight) { myNamedRectangle.setSize(newWidth, newHeight); repaint(); }
This approach gives you a persistent, referenceable object for your rectangle, letting you manipulate or query it whenever you need to.
内容的提问来源于stack exchange,提问作者224634

