Java GUI中图片无法在指定坐标点绘制的问题求助
Fixing Your Java GUI Image Drawing Issue
Hey there! Let's work through why your image isn't showing up at the specified point and get it working properly. As a new programmer, it's totally normal to hit these Swing GUI quirks—let's break down the issues and fix them step by step.
Key Problems in Your Current Code
- Your
Trialclass doesn't inherit from a Swing container (likeJPanel), and you never create a visibleJFrameto display your button or drawing area. Right now, your code just creates aTrialobject but never shows any window! - Using
getGraphics()directly is unreliable. This method gives you a temporaryGraphicsobject that gets wiped out when the window is redrawn (e.g., if you minimize and restore the window). Swing has a built-in painting lifecycle you should use instead. - You aren't triggering a proper repaint when you want to draw the image—Swing needs to know when to refresh the screen.
Fixed Code with Explanations
Here's a revised version of your code that works as intended, with comments explaining each change:
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; // Make Trial inherit from JPanel so it can act as a drawing surface public class Trial extends JPanel { private BufferedImage image = null; private JButton button; // Variables to track if we should draw the image, and where private boolean shouldDrawImage = false; private Point drawPoint; Trial(){ // Initialize your point array Point[] array = new Point[5]; array[0] = new Point(150, 200); drawPoint = array[0]; // Set the default draw point // Create and configure the button button = new JButton("Paste"); button.setBounds(875, 525, 125, 50); // Load the image try{ // Note: You might want to use a relative path instead of absolute for portability image = ImageIO.read(new File("C:\\GUI Program\\src\\com\\company\\Square.PNG")); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Failed to load image!", "Error", JOptionPane.ERROR_MESSAGE); } // Button click listener: instead of drawing directly, trigger a repaint button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shouldDrawImage = true; // Mark that we need to draw the image repaint(); // Tell Swing to refresh the panel } }); // Set up the JFrame (the main window) JFrame frame = new JFrame("Image Paste Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000, 600); // Set window size to fit your button and drawing area frame.setLayout(null); // Using null layout for your current bounds setup (note: layout managers are better for most cases) // Add the button and this panel to the frame frame.add(button); frame.add(this); // Add our JPanel (which handles drawing) to the frame frame.setVisible(true); // Make the window visible } // Override paintComponent to handle custom drawing (Swing's recommended way) @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Always call the parent's paintComponent first to clear the panel // Only draw the image if we have it and shouldDrawImage is true if (shouldDrawImage && image != null && drawPoint != null) { g.drawImage(image, drawPoint.x, drawPoint.y, this); // Use this as the ImageObserver } } public static void main (String args[]){ // Run Swing code on the Event Dispatch Thread (EDT) for safety SwingUtilities.invokeLater(() -> new Trial()); } }
What Changed & Why
- Inherited
JPanel: This turns yourTrialclass into a Swing component that can handle custom drawing and be added to a window. - Added
shouldDrawImageanddrawPoint: These variables let us track when and where to draw the image, so thepaintComponentmethod knows what to do when the panel is redrawn. - Created a
JFrame: This is the main window that displays your button and drawing area—without this, nothing is visible! - Used
paintComponent: This is the correct place to do custom drawing in Swing. Thesuper.paintComponent(g)call ensures the panel is cleared before drawing, preventing artifacts. - Triggered
repaint()in the button listener: Instead of drawing directly, we tell Swing to refresh the panel, which callspaintComponentautomatically. - Ran code on the EDT: The
SwingUtilities.invokeLatercall ensures all Swing operations run on the Event Dispatch Thread, which is required for thread safety in Swing.
Testing the Code
- Make sure your image path is correct (double-check the file location and spelling).
- Compile and run the code—you'll see a window with your "Paste" button.
- Click the button, and your image will appear at the
(150, 200)point you specified. Even if you minimize and restore the window, the image will stay visible!
内容的提问来源于stack exchange,提问作者Shubham Goel
相关产品推荐
相关产品推荐

