gpt4 book ai didi

java - 如何编写高效的背景图像

转载 作者:行者123 更新时间:2023-12-02 04:29:06 24 4
gpt4 key购买 nike

请问我正在用 java 编写 2D 游戏,但是我的背景图像没有随 JFrame 一起加载,因为它是可调整大小的,所以当我拖动 JFrame 时它会加载

 import javax.swing.*;
import java.awt.*;
public class imageLearn1 extends JFrame{
private Image im;
private JPanel p1;

public imageLearn1(){
this.setSize(300,400);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1=new paintIt();
this.add(p1);
}
class paintIt extends JPanel{
public paintIt(){
ImageIcon ima=new ImageIcon("ballfall3.jpg");
im=ima.getImage();

im=im.getScaledInstance(200,-1,Image.SCALE_DEFAULT);
}

public void paintComponent(Graphics g){
super.paintComponent(g);
if(im!=null){
g.drawImage(im,0,0,300,400,this);
}
}
}


public static void main(String[]args){
new imageLearn1();

}
}

最佳答案

在使框架可见之前,您必须将组件添加到框架中。代码的顺序应该是:

p1=new paintIt();
this.add(p1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,400);
this.setLocationRelativeTo(null);
this.setVisible(true);

此外,类名称应以大写字符开头。你的类名应该是“PaintIt”。

关于java - 如何编写高效的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com