在主题中:当我在JFrame中更改JPanel时,我失去了焦点。我有班级游戏,动作,按钮。 我也在课堂上绘制游戏舞台。当我在JFrame中更改JPanel时,我失去了焦点
起初在游戏中我有动作面板,其中包含按钮,在按钮NewGame后我改变面板在游戏阶段,但我不能控制船,我飞。
如何解决它或如何做到这一点不同?
Action.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.*;
@SuppressWarnings("serial")
public class Action extends JPanel {
public static final int xxx = 800;
public static final int yyy = 600;
private Button buttonPanel;
public Action(Game game) {
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
buttonPanel = new Button(game);
add(buttonPanel);
setVisible(true);
}
}
Button.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Button extends JPanel implements ActionListener{
public static final int xxx = 100;
public static final int yyy = 300;
private JButton NewGame;
private JButton Scores;
private JButton Exit;
private Game game;
public Button(Game game) {
NewGame = new JButton("NewGame");
Scores = new JButton("Scores");
Exit = new JButton("Wyjście");
this.game=game;
NewGame.addActionListener(this);
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
add(NewGame);
add(Scores);
add(Exit);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == NewGame){
game.setPanel("stage");
}
;
}
}
Game.java
@SuppressWarnings("serial")
public class Game extends JFrame {
private Action menu;
private static Stage stage = new Stage();
public Game() {
super("Lunar Lander");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Stage.WIDTH,Stage.HEIGHT);
setMinimumSize(new Dimension(400,300));
this.setResizable(true);
//stage = new Stage(0);
menu = new Action(this);
add(menu);
pack();
//setPanel("stage");
setVisible(true);
}
public void setPanel(String panel) {
if (panel=="stage") {
remove(menu);
add(stage);
pack();
} else if (panel=="menu") {
remove(stage);
add(menu);
pack();
}
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Game();
}
});
Thread a = new Thread(stage);
a.start();
while (a.isAlive()) {}
Scores scores = new Scores();
scores.changeScores(stage.getPlayer().getName(),stage.getPlayer().getPoints());
}
}
为什么'setVisible(true/false)'为每个组件?为什么不简单使用[__CardLayout__](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html),而不是手动添加/删除?这个'Thread'是什么?这个“舞台”班在哪里?您是否在使用'KeyListener's来控制上述的'SHIP'? –
此主题适用于动画,Stage实现Runnable。我正在使用键绑定,将其添加到Stage Stage中。 CardLayout并不是最好的解决方案,因为我想要做简单的菜单,其中包含按钮:“新游戏”,“退出”。推后“新游戏”manu应该消失和舞台出现。当游戏中的一切都在绘画时,舞台就像棋盘一样。 – user3191398
1)对于一个空间中的许多组件,使用['CardLayout'](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html)示例](http://stackoverflow.com/a/5786005/418556)。 2)为了更快地获得更好的帮助,请发布[MCVE](http://stackoverflow.com/help/mcve)(最小完整和可验证示例)。 –