Java drawImage不是绘图
这就是我的代码的工作原理Java drawImage不是绘图,java,user-interface,drawimage,Java,User Interface,Drawimage,这就是我的代码的工作原理 class Main extends JFrame implements Runnable { public Main() { //init everything } public void start() { running = true; Thread thread = new Thread(this); thread.start(); } public void run() {
class Main extends JFrame implements Runnable {
public Main() {
//init everything
}
public void start() {
running = true;
Thread thread = new Thread(this);
thread.start();
}
public void run() {
while(running) {
render();
}
}
public void render() {
Image dbImage = createImage(width, height);
Graphics dbg = dbImage.getGraphics();
draw(dbg);
Graphics g = getGraphics();
g.drawImage(dbImage, 0, 0, this);
g.dispose();
}
public void draw(Graphics g) {
for(int y=0; y < map.length; y++) {
for(int x=0; x < map.length; x++) {
g.drawImage(map.map[x + y* map.MAP_DIM], x*MAP_DIM, y*MAP_DIM, this);
}
}
}
public static void main(String... args) {
Main main = new Main();
main.start();
}
}
class Main扩展JFrame实现可运行{
公用干管(){
//一切
}
公开作废开始(){
运行=真;
螺纹=新螺纹(此);
thread.start();
}
公开募捐{
(跑步时){
render();
}
}
公共无效呈现(){
Image dbImage=createImage(宽度、高度);
Graphics dbg=dbImage.getGraphics();
绘制(dbg);
Graphics g=getGraphics();
g、 drawImage(dbImage,0,0,this);
g、 处置();
}
公共空间绘制(图g){
对于(int y=0;y
但是什么也没画,我看到的都是灰色。有人知道问题出在哪里吗?我尝试在draw()方法的末尾执行repaint(),但仍然没有任何结果。您不应该使用Java中的Swing自行管理绘图 您必须让线程通过自己的线程调用适当的重绘方法。这是通过调用
JComponent
的paint(Graphics g)
完成的。现在,您不应该重写该方法,而应该改为paintComponent(Graphics g)
因此,您应该将绘制方法从线程移动到适当的绘制方法:
public void run() {
while (running)
repaint();
}
public void paintComponent(Graphics g) {
draw(g);
}
请注意,您应该以固定的帧速率调用重绘,并使用双缓冲以避免闪烁
一个更简单的解决方案是嵌入一些已经为这类工作准备好的东西,比如框架,它工作得非常好。“Swing程序应该覆盖
paintComponent()
,而不是覆盖paint()
”。此外,Swing GUI对象应仅在上构造和操作。在进行此类编码之前,请阅读教程,否则,您可能会做出所有错误的假设,并像上面所发布的那样创建无法正常工作的代码。您将阅读教程,了解更多有用的提示。使用双缓冲以避免闪烁
。。。Swing组件默认为双缓冲。。。这并不是说人们应该回避这个问题,因为默认机制可能并不总是满足人们的需要;)+从我这里得到1