Java改变JFrame问题的内容
我试图改变Jframe的内容,使其从菜单屏幕变为游戏本身。这就像你点击开始游戏,然后你就可以玩游戏了。到目前为止,我已经成功地更改了内容,但无法从我的代码中检测到游戏的控件。例如,我按下空格键,这样游戏中的角色就会射击,但每当我按下空格键时,我都不会注意到任何事情发生。我看到过与此非常相似的主题,但这些都没有帮助我解决问题。下面是我的代码:Java改变JFrame问题的内容,java,swing,Java,Swing,我试图改变Jframe的内容,使其从菜单屏幕变为游戏本身。这就像你点击开始游戏,然后你就可以玩游戏了。到目前为止,我已经成功地更改了内容,但无法从我的代码中检测到游戏的控件。例如,我按下空格键,这样游戏中的角色就会射击,但每当我按下空格键时,我都不会注意到任何事情发生。我看到过与此非常相似的主题,但这些都没有帮助我解决问题。下面是我的代码: package rtype; import javax.swing.JButton; import javax.swing.JFrame; import
package rtype;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Rtype extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public Rtype() {
setSize(1020, 440);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("PROJECT JAEGER");
setResizable(false);
setVisible(true);
JButton startButton = new JButton("START GAME");//The JButton name.
add(startButton);//Add the button to the JFrame.
startButton.addActionListener(this);//Reads the action.
}
public static void main(String[] args) {
new Rtype();
}
public void actionPerformed(ActionEvent i) {
getContentPane().removeAll();
add(new Board());
setVisible(true);
System.out.println("The Button Works!");//what the button says when clicked.
}
}
调用
add(新板())代码>召唤游戏。棋盘是游戏的类别。解决方案非常简单。更改帧中的内容后,需要调用revalidate
使更改生效。只需将这行代码添加到actionPerformed
的末尾,它就可以工作了:
revalidate();
另一个更改:添加按钮后,将setVisible(true)
移到末尾。仍然相同:(以下是执行的操作的当前内容:public void actionperformed(ActionEvent i){getContentPane().removeAll();add(new Board());System.out.println(“按钮工作!”);//单击按钮时显示的内容。revalidate();setVisible(true);}我通过添加revalidate
并放置setVisible(true)来测试它
最后,它成功了。我没有你的棋盘
类,所以我无法确定测试,但你也可以尝试给棋盘输入焦点,在添加后在棋盘上调用'requestFocus'。我的意思是它确实会改变内容,但当我按下某些控件(如空格)时,游戏中的角色会射击,但角色会被射杀没有。对于一个空间中的多个组件,请使用如图所示的。