gpt4 book ai didi

Java - 暂停一个方法?

转载 作者:行者123 更新时间:2023-12-01 12:45:40 24 4
gpt4 key购买 nike

我的一个菜单只是一张图像和一个“返回”按钮。问题是,后退按钮总是在图像之前加载,即使它在代码中位于图像之后。

有什么办法可以解决这个问题吗?我是编程新手,所以我能想到的最好方法是以某种方式暂停该方法,比如 3 秒钟,同时加载图片,然后加载后退按钮。

我尝试过使用 thread.sleep(3000) 但如果我这样做,图像根本不会加载!也许我用错了?

public void render(Graphics g){

if(Instscrn==true){
g.drawImage(InstructionScreen, 0, 0, Resources.sp);

if(instclose){
g.setFont(new Font("Arial", Font.PLAIN, 30));
g.setColor(Color.BLACK);
g.drawString("Back", 672, 552);
}

使用 thread.sleep

public void render(Graphics g){

if(Instscrn==true){
g.drawImage(InstructionScreen, 0, 0, Resources.sp);

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

if(instclose){
g.setFont(new Font("Arial", Font.PLAIN, 30));
g.setColor(Color.BLACK);
g.drawString("Back", 672, 552);
}

感谢您的帮助!

最佳答案

您可以在渲染(Graphics g)上加载图像,而无需暂停任何方法:

boolean inited = false;
Image i;
public void render(Graphics g){
if(!inited) {
//here, init your image, for example: download files from web or load resources
try {
i = ImageIO.read(new File(""));//loading image
} catch (IOException e) {
e.printStackTrace();//error
}
inited=true;
}
g.drawImage...
}

您无法暂停方法,但可以暂停线程(使用方法):

public static void main(String[] args) throws InterruptedException {
final Thread pauseable = new Thread("Pauseable method/thread") {
//Pauseable method
public void run() {
for(int i=0; i<20; i++) {
System.out.println("Working");
sleepMethod();
}
}
//Sleep for 1 seconds
public void sleepMethod() {
try {
sleep(1000);
} catch(Throwable t){}
}
};
pauseable.start();
JFrame f = new JFrame();
JButton pause = new JButton("Pause");
JButton start = new JButton("Resume");
pause.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
try {
pauseable.suspend();
} catch(Throwable t) {
t.printStackTrace();
}
}});
start.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
try {
pauseable.resume();
} catch(Throwable t) {
t.printStackTrace();
}
}});

//STYLE OF BUTTONS ETC.:
JPanel p = new JPanel(new GridLayout(1,2));
p.add(pause);
p.add(start);
f.getContentPane().add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);


pauseable.join(); //If you want wait to end of running method
System.out.println("Method pauseable.run() was ended!");
}

关于Java - 暂停一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725436/

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