我目前正在尝试在JPanel上绘制图像的大网格,然后每秒将面板添加到JFrame 60次。在绘制到由具有“ extends JPanel”的类创建的面板并使用paintComponent(Graphics g)绘制到该JPanel时,我具有此功能。但是,这样做的问题在于,由于每秒每秒调用该类60次(每次都调用一次paintComponent),因此该应用程序只能以2-3fps的速度运行。我想出的解决方案是使用以下代码,通过创建必须手动调用的绘制方法,将图像仅绘制到JPanel一次,然后简单地每秒将该JPanel添加到JFrame上60次。
public class Testing extends JPanel {
public static void main(String[] args) {
testing.run(frame); //This is called by another class in the program
}
JFrame frame = new JFrame();
JPanel panelContainingDrawnImages;
Image[][] MAP; // Initialized based on the world.txt file it receives
public void tick() { // Is called 60 times a second
frame.add(this); // Add the class's main panel, - which now has the Images painted to it - to the frame used by all classes in the application
}
public void drawImageToPanel(Graphics g) {
for (int c = 0; c < MAP.length; c++) { // The x axis of the game's map
for (int r = 0; r < MAP[c].length; r++) { // The y axis of the game's map
g.drawImage(MAP[c][r], xPos, yPos, null);
}
}
}
public void run(JFrame frame) {
frame = this.frame; // The JFrame from this method is passed in from another class
Graphics g = getGraphics();
drawImageToPanel(g);
}
}
但是,由于某些原因,该行
Graphics g = getGraphics();
返回null,因此调用
drawImageToPanel(g);
失败,绘制任何图形后立即返回NullPointerException。
我的问题是:如何多次调用JFrame.add(panel)方法多次(每秒60次),一次只能将一堆图像绘制到JPanel。这似乎无法使用paintComponent()来实现,因为每次调用class.tick()(每秒被调用60次)时都会运行,这意味着一次又一次绘制Image的2D数组,这意味着该程序仅以几fps的速度运行,而不是所需的60 fps。我也在努力使用必须手动调用的绘图方法来完成此任务,
g = getGraphics();
只返回null。我该怎么办?