gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:15 24 4
gpt4 key购买 nike

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

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);
}
}

我正在加载的图像是一张 map ,我想通过在正确的坐标中绘制点来指示某些对象的位置。因此,在这里向 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 在他的 comment 中所写内容的演示:“应该更改组件的状态变量,然后调用重绘”:

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;}
}

关于java - 如何将参数传递给paintComponent以便在不同的类中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com