如何将参数传递给 paintComponent 以便在不同的 class 中调用它?

How can I pass an argument to paintComponent in order to call it in a different class?

在我的主 class 中,我有以下代码从我的机器加载图像并将其显示在框架上以在其上绘制东西:

public class ShowMap extends JPanel {

    private static final int WIDTH = 1340;
    private static final int HEIGHT = 613;

    public void main(String args[]) {
        JFrame frame = new JFrame("MAP");
        frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        frame.setMinimumSize(new Dimension(WIDTH, HEIGHT));
        frame.setMaximumSize(new Dimension(WIDTH, HEIGHT));
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = (JPanel)frame.getContentPane();
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon("map.png"));
        panel.add(label);
    }
}

我正在加载的图像是一张地图,我想通过在正确的坐标中绘制点来指示某些对象的位置。因此,重要的是在这里指示 DrawPoint class(下)什么坐标应该得到点。

此外,如果您能解释如何擦除已绘制的点,我将不胜感激。

我的搜索让我得到以下结果,但是一旦我将 int coordx, int coordy 添加到该方法的参数中,它就不再突出显示,而且我不知道如何在 ShowMap 同时将坐标作为参数传递。

public class DrawPoint extends JPanel {

    private int coordx;
    private int coordy;

    public void paintComponent(Graphics g, int coordx, int coordy){
        g.setColor(Color.BLACK);
        g.fillOval(coordx,coordy,8,8);
    }
}

这是 MadProgrammer 在他的 中所写内容的演示:"should be changing a state variable of the component and then calling repaint" :

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SwingTest extends JFrame {

    private static final int SIZE = 300;
    private DrawPoint drawPoint;

    public SwingTest()  {

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        drawPoint = new DrawPoint();
        drawPoint.setPreferredSize(new Dimension(SIZE, SIZE));
        add(drawPoint);
        pack();
        setVisible(true);
    }

    //demonstrate change in DrawPoint state
    private void reDraw() {

        Random rnd = new Random();
        Timer timer = new Timer(1000, e -> { //periodically change coordinates and repaint
            drawPoint.setCoordx(rnd.nextInt(SIZE));
            drawPoint.setCoordy(rnd.nextInt(SIZE));
            drawPoint.repaint();
        });
        timer.start();
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(() ->    new SwingTest().reDraw());
    }
}

class DrawPoint extends JPanel {

    private int coordx, coordy;

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillOval(coordx,coordy,8,8);
    }

    //use setters to change the state 
    void setCoordy(int coordy) {    this.coordy = coordy; }
    void setCoordx(int coordx) {this.coordx = coordx;}
}