我正在尝试创建一个游戏,我从加载屏幕开始,它将加载所有需要的文件。我想显示完成的百分比,但它不起作用。JPanel Loading 仅在 Loading_files 完成后 repaints() 。我不知道怎么了。
主.java
package Main;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
//-------------- Final Variables --------------
//Screen Related
public final static int JFRAME_WIDTH = 800;
public final static int JFRAME_HEIGHT = 600;
public final static Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
public final static int SCREEN_WIDTH = SCREEN_SIZE.width;
public final static int SCREEN_HEIGHT = SCREEN_SIZE.height;
//Game Related
public final static String NAME = "Xubris";
public final static String IMAGE_DIRECTORY = System.getProperty("user.dir") + "\\images\\";
public static final int FPS = 1000 / 36;
//-------------- Dynamic Variables --------------
//Global
public static JFrame main;
public static void main(String[] args) {
//Start the Loading screen
Loading load = new Loading();
main = new JFrame(NAME);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(JFRAME_WIDTH, JFRAME_HEIGHT);
main.setLocation((SCREEN_WIDTH-JFRAME_WIDTH)/2, (SCREEN_HEIGHT-JFRAME_HEIGHT)/2);
//Add Content
main.getContentPane().add(load);
main.setResizable(false);
main.setUndecorated(false);
main.setVisible(true);
}
}
加载.java
package Main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Loading extends JPanel implements Runnable{
//Pictures
BufferedImage background;
//-------------- Final Variables --------------
private final int num_of_files = 32;
//-------------- Dynamic Variables --------------
//Global Variables
private double loading_percentage = 0;
private int num_of_loaded_files = 0;
public Loading(){
try {
background = ImageIO.read(new File(Main.IMAGE_DIRECTORY + "Background_Loading.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
//Start the thread
new Thread(new LoadingFiles()).start();
new Thread(this).start();
}
public void paint(Graphics g){
g.drawImage(background, 0, 0, this);
for(int i = 0; i < loading_percentage; i=i+15){
g.setColor(new Color(20,241,47));
g.drawRect(180 + (i/15)*(50+10), 375, 50, 50);
}
}
@Override
public void run(){
while(true){
repaint();
}
}
class LoadingFiles implements Runnable{
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
num_of_loaded_files++;
loading_percentage = (num_of_loaded_files/num_of_files)*100;
if(num_of_loaded_files!=32)
run();
}
}
}