我一直在尝试遵循一个简单的在线教程(https://www.youtube.com/watch?v=1gir2R7G9ws)。当我尝试输入他输入的代码时,我没有得到相同的结果。我输入的一些内容最终会出现无法使用的错误。当我尝试使用 GetBufferStrategy 时尤其会发生这种情况。我不太确定我的代码有什么问题。我确实需要一些帮助。
这是我得到的:
package components;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class Window {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private Thread thread;
private boolean running = false;
public synchronized void start(){
thread = new Thread();
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running=false;
}catch(Exception e) {
e.printStackTrace();
}
}
public void run(){
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick(){
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs==null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0,873,374);
g.dispose();
bs.show();
}
private void createBufferStrategy(int i) {
}
private BufferStrategy getBufferStrategy() {
return null;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Mr. Krebs");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(1000, 700));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
最佳答案
你的类应该扩展Canvas
:
public class Window extends Canvas {
...
}
在您的 render()
方法中,您使用 this.getBufferStrategy
和 this.createBufferStrategy
。由于这两条指令调用 Canvas
类中的方法,如果您不键入 extends Canvas
,您将收到错误,因为无法找到这些方法。
关于java - 如何更改窗口的颜色(缓冲区策略问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334575/