如何将参数传递给paintComponent以便在其他类中调用它?

时间:2018-11-23 23:32:30

标签: java swing graphics awt custom-painting

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

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类(如下)应使用什么坐标。

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

我的搜索导致我发现以下内容,但是,一旦我在方法的参数中添加int coordx, int coordy,它就不再突出显示,并且我不知道如何在{{1 }},同时将坐标作为参数传递。

ShowMap

1 个答案:

答案 0 :(得分:0)

这是MadProgrammer在其comment中写的内容的演示:“应更改组件的状态变量,然后调用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;}
}