在我的主类中,我有以下代码来从我的机器加载图像,并将其显示在框架上以在其上绘制东西:
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
添加到该方法的参数中,它就不再突出显示,而且我不知道如何在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在其评论中所写内容的演示:"应该更改组件的状态变量,然后调用重新绘制":
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;}
}