gpt4 book ai didi

java - 小程序中不显示按钮

转载 作者:行者123 更新时间:2023-12-01 15:07:05 25 4
gpt4 key购买 nike

以下是我的小程序游戏的精简代码:

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;

public class Game extends Applet implements KeyListener, Runnable {
Button options = new Button("Options");
Thread thread = new Thread(this);

public void init() {
addKeyListener(this);
thread.start();
}

public void paint(Graphics graphics) {
// draw stuff
}

public void run() {
try {
while (true) {
thread.sleep(40);
repaint();
}
} catch (InterruptedException exception) {}
}

public void keyPressed(KeyEvent keyEvent) {
switch (keyEvent.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
// pause game
add(options);
}
}

public void keyReleased(KeyEvent keyEvent) {}
public void keyTyped(KeyEvent keyEvent) {}
}

我的游戏按预期运行。但是,当用户按 Esc 时,我想暂停游戏并显示选项按钮。

问题是,当我按 Esc 时,它会按预期暂停游戏。但是它不会在屏幕上显示该按钮。我试图寻找解决方案但无济于事。到底发生了什么?

最佳答案

对我来说工作得很好......

public class TestApplet02 extends Applet implements KeyListener, Runnable {

Button options = new Button("Options");
Thread thread = new Thread(this);
int y = 0;

public void init() {
thread.start();
}

@Override
public void start() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setLayout(new BorderLayout());
addKeyListener(TestApplet02.this);
}
});
}

public void paint(Graphics graphics) {
super.paint(graphics);
Graphics2D g2d = (Graphics2D) graphics;
y++;
if (y > getHeight()) {
y = 0;
}
g2d.drawLine(0, y, getWidth(), y);
}

public void run() {
try {
while (true) {
thread.sleep(40);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
repaint();
}
});
}
} catch (InterruptedException exception) {
}
}

public void keyPressed(KeyEvent keyEvent) {
switch (keyEvent.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
// pause game
add(options);
invalidate();
revalidate();
}
}

public void keyReleased(KeyEvent keyEvent) {
}

public void keyTyped(KeyEvent keyEvent) {
}
}

从 TrashGod 提供的链接...

In an applet, the GUI-creation task must be launched from the init method using invokeAndWait; otherwise, init may return before the GUI is created, which may cause problems for a web browser launching an applet. In any other kind of program, scheduling the GUI-creation task is usually the last thing the initial thread does, so it doesn't matter whether it uses invokeLater or invokeAndWait.

已更新

我遇到的主要问题是:

在您的转义键处理程序中,如果方向为 0,则暂停选项将永远不会激活...

case KeyEvent.VK_ESCAPE:
direction = -direction;

if (direction < 0) {
add(options);
} else {
remove(options);
}

我必须做的另一件事是调用revalidate...

invalidate();
revalidate();
repaint();

关于java - 小程序中不显示按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12830923/

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