You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Trial class doesn't inherit from a Swing container (like JPanel), and you never create a visible JFrame to display your button or drawing area. Right now, your code just creates a Trial object but never shows any window!
  • Using getGraphics() directly is unreliable. This method gives you a temporary Graphics object 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

  1. Inherited JPanel: This turns your Trial class into a Swing component that can handle custom drawing and be added to a window.
  2. Added shouldDrawImage and drawPoint: These variables let us track when and where to draw the image, so the paintComponent method knows what to do when the panel is redrawn.
  3. Created a JFrame: This is the main window that displays your button and drawing area—without this, nothing is visible!
  4. Used paintComponent: This is the correct place to do custom drawing in Swing. The super.paintComponent(g) call ensures the panel is cleared before drawing, preventing artifacts.
  5. Triggered repaint() in the button listener: Instead of drawing directly, we tell Swing to refresh the panel, which calls paintComponent automatically.
  6. Ran code on the EDT: The SwingUtilities.invokeLater call ensures all Swing operations run on the Event Dispatch Thread, which is required for thread safety in Swing.

Testing the Code

  1. Make sure your image path is correct (double-check the file location and spelling).
  2. Compile and run the code—you'll see a window with your "Paste" button.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:38:12