我的图形引擎库中有这段代码:
package WG;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class window {
public static boolean running=true;
public static int WIDTH = 800, HEIGHT = 600;
public static String TITLE = "New Window";
public static JFrame frame;
public static int[] pixels;
public static BufferedImage img;
public static Thread thread;
public window(){}
public static void create() {
img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
frame = new JFrame("WINDOW");
//frame.setResizable(false);
frame.setLayout(new FlowLayout(FlowLayout.LEADING,0,0));
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
//frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void render() {
BufferStrategy bs=frame.getBufferStrategy();
if(bs==null){
frame.createBufferStrategy(2);
return;
}
Graphics g= bs.getDrawGraphics();
g.drawImage(img, 0,0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
public static void clear_screen(){
for (int i = 0; i < WIDTH * HEIGHT; i++)
pixels[i] =0;
};
}
和我的主要java文件中的这段代码:
import WG.*;
public class Main_window{
private static boolean running = true;
public static window wind = new window();
public static Thread thread;
public static void main(String[] args) {
window.create();
start();
}
public static void start() {
while (running) {
window.clear_screen();
Forms.drawRect(0, 0, 100, 100);//my own method
wind.render();
}
}
}
我在这里有两个问题:
1-->窗口上的图像显示在负坐标上(矩形不是100x100)
如果我重新调整窗口大小,图像试图在 0 0 坐标处绘制,但随后又在负坐标处绘制。
2-->我得到2个不同的错误:
a) 组件必须是有效的对等体Graphics g= bs.getDrawGraphics();
b) 缓冲区尚未在bs.show();
这些问题是什么?
我在 YouTube这个频道上看到他使用了 Canvas 和其他东西,但他没有收到任何错误(我知道不要将挥杆与 awt 混合)
编辑
//from graphics library
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
}
//from the main file
public static void start() {
while (running) {
window.clear_screen();
Forms.drawRect(0, 0, 100, 100);//my own method
wind.frame.repaint();
}
}