我正在 Netbeans 中用 Java 编写模拟,实际的非图形编码大部分已经完成。但是,我想做一个图形化的实现,我使用图标来表示模拟中变化的变量。
模拟模拟卡车在道路上行驶,我想要一个图标来代表每辆卡车。代码将每辆卡车和每条道路显示为一个单独的对象,每个对象都有自己的属性,但只有少数属性需要在图形实现中建模。例如,每辆卡车的位置是道路的一个属性,显示卡车沿着道路行驶了多远。
在图形界面中建模的最简单方法是什么?我假设我需要为 Netbeans 中的图形结构分配一个图标,然后让它根据道路的距离属性自行更新,但我不知道如何处理这个问题。
我们将不胜感激。
最佳答案
使用 Graphics 类,您可以绘制道路、汽车(使用图像),并使用 Swing Timer 制作动画。
要绘制汽车,您可以使用将图像绘制到屏幕上
public class Map extends JPanel {
BufferedImage car1;
BufferedImage car2;
BufferedImage car3;
public Map(){
try {
car1 = ImageIO.read(getClass().getResource("somecarimage.png"));
car3 = ImageIO.read(getClass().getResource("somecarimage.png"));
car3 = ImageIO.read(getClass().getResource("somecarimage.png"));
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
// use the drawImage method
g.drawImage(car1, xLocation, yLocation, height, width, this);
g.drawImage(car2, xLocation, yLocation, height, width, this);
g.drawImage(car2, xLocation, yLocation, height, width, this);
}
}
如您所见,我在屏幕上画了三辆汽车。您可以将您的类与数据一起用作 xLocation
和 yLocation
如果你想让汽车动起来,你可以使用 Swing Timer
Timer timer = new Timer(100, new ActionListener(){ // causes an action every 100 millis
public void actionPerformed(ActionEvent e){
// change the xLocation and yLocation of each car
car1.xLocation += 5;
car1.yLocation += 5;
car2.xLocation += 5;
car2.yLocation += 5;
car3.xLocation += 5;
car3.yLocation += 5;
repaint();
}
});
timer.start();
您可以在 actionPerformed 的某处使用 if 语句告诉计时器何时停止。
Javadocs 和教程
Timer javadoc | Timer tutorial | Graphics javadoc | Graphics tutorial
关于java - 如何将程序中的变量分配给 Swing 中的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20611200/