【发布时间】:2014-05-13 16:38:48
【问题描述】:
我正在尝试制作一个图形用户界面,其中页面中间有一个矩形车辆对象,关于 x 坐标和车辆两侧的两个矩形对象。
我正在扩展一个JPanel,所以我在run方法中调用repaint来调用paintComponent方法,但是我什至没有进入paintComponent方法。此外,由于我使用的是 Graphics2D,我是否必须做一些不同的事情?
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Display extends JPanel implements Runnable{
public static final int frameWidth=1300;
public static final int frameHeight=800;
public double score;
public double updateTimeInterval=25;
public double prevUpdatedTime=0;
public Display(){
JFrame frame = new JFrame();
frame.setSize(frameWidth, frameHeight);
frame.setTitle("You are playing HoverTeam!!!");
frame.setVisible(true);
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
System.out.println("completed constructor.");
}
public void paintComponent(Graphics g){
System.out.println("currently painting.");
Graphics2D g2 = (Graphics2D) g;
/*
* Testing with random GameState
*/
double[] pos = {28,6,Math.PI/8};
double[] vel = {5,5,0};
int[] nearList = {4,8,7,5};
GameState gs = new GameState(pos,vel,2,2,nearList,3);
//GameState gs = GameClient.getGameState();
/*
* Drawing the vehicle in the center of the screen with regards to the x-coordinate and then referencing the walls to it.
*/
Path2D.Double vehic = gs.getVehicleShapePath(frameWidth/2, gs.getPosition()[1]);
g2.draw(vehic);
int[] nearObstHeights = gs.getNearObstList();
double vehiclePast = gs.getPosition()[0]%5; //distance that the vehicle is past the second obstacle--reference to where to draw obstacles
for (int i =0; i<nearObstHeights.length;i++){
Rectangle2D.Double obstacle = new Rectangle2D.Double(frameWidth/2 -vehiclePast+5*(i-1),nearObstHeights[i],1,nearObstHeights[i]);
g2.draw(obstacle);
}
score = gs.getPosition()[0]/5;
g.drawString("Score:"+score, frameWidth/2, frameHeight-10);
}
public void run(){
/*
* No maximum score, game goes on forever.
*/
System.out.println("entereed run method.");
while (true){
long currentTime = System.currentTimeMillis();
if (currentTime-prevUpdatedTime>updateTimeInterval){
System.out.println("entered if statement");
prevUpdatedTime = currentTime;
repaint();
System.out.println("should have just repainted.");
}
}
}
public static void main(String[] args){
(new Thread(new Display())).start();
}
}
谢谢
【问题讨论】:
-
你认为你在哪里实例化一个对象
Display,它会使用paintComponent(即它在GUI中显示)? -
是的,您将一些普通的 JPanel 添加到您的 JFrame 中,而不是将 Display 类的任何对象添加到显示的任何内容中。另外,顺便说一句,您的 paintComponent 方法似乎很危险,因为您似乎在此方法中有代码逻辑,它会更改您的类的状态,而这不应该是。
-
我想通过在main方法中调用(new Thread(new Display())).start();我将调用 Display 对象的 run 方法,当我在 run 方法中调用 repaint 时,它又调用 paintComponent。
-
@user3014093 调用 start() 肯定会执行 run()。但是您永远不会在您的 GUI 中放置任何 Display 对象。 Display 是一个 JPanel,它必须放在 Frame 中。在弄乱paintComponent 之前,只需尝试制作一个简单的GUI。您缺少对 Swing 的一些关键理解。
-
是的,目前我有paintComponent 方法调用同步方法来获取gameState,然后绘制它。但是,为了测试它,我只是做了一个示例 gameState 并想看看它是否显示。为什么这么危险?
标签: java swing jpanel paintcomponent graphics2d