我想在Java上使用Swing组件(Boggle类型的游戏)做一个小游戏。 现在我已经设置了它的方式,它基本上可以立即打开游戏 - 但我希望有一个启动窗口有两个按钮 - “教程”和“播放”。我已经有了功能(我的教程按钮只是打开一个包含所有东西的新窗口)我只是不确定如何创建第二个JFrame,然后在按Play时切换到它(或者更确切地说,创建一个JFrame,然后切换到JButton按下时已经创建的那个)。我想我可能会导致新的JFrame在同一位置打开,而旧的JFrame会变得不可见 - 但我希望能有一个更简单的解决方案。更改布局/框架响应按钮按
我也想在游戏完成时做到这一点,自动切换到一个小统计页面 - 所以任何信息将不胜感激。
这是我迄今为止的情况下,如果你们想看我的代码(我还没有挂上回车键发送userWord进行验证和评分在我的其他类,或填充在tileGrid中图块对象,或定时器....但将其随后所有的来了!)
public class Game implements Runnable {
public void run(){
final JFrame frame = new JFrame("Boggle");
frame.setLocation(500,200);
// Input - holds typing box
final JLetterField typingArea = new JLetterField(1);
typingArea.setFocusTraversalKeysEnabled(false);
typingArea.setEditable(true);
typingArea.setFocusable(true);
typingArea.requestFocusInWindow(); //also this request isn't being granted..
//if anyone could explain why i would love you
// I want the focus on the TextField on startup
frame.add(typingArea, BorderLayout.SOUTH);
typingArea.addKeyListener(new KeyAdapter() {
public void keyPressed (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) { // enter key is pressed
String userWord = typingArea.getText().toLowerCase();
typingArea.setText("");
}
}
});
final JLabel status = new JLabel("Running...");
// Main playing area
GridLayout tileGrid = new GridLayout(4,4);
final JPanel grid = new JPanel(tileGrid);
frame.add(grid, BorderLayout.CENTER);
// Reset button
final JPanel control_panel = new JPanel();
frame.add(control_panel, BorderLayout.NORTH);
final ImageIcon img = new ImageIcon("Instructions.png", "My Instructions...");
final JButton info = new JButton("Help");
info.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame infoFrame = new JFrame("Tutorial");
infoFrame.setLocation(500,50);
JLabel tutorialImg = new JLabel(img);
int w = img.getIconWidth();
int h = img.getIconHeight();
infoFrame.setSize(w, h);
infoFrame.add(tutorialImg);
infoFrame.setVisible(true);
}
});
control_panel.add(info);
// Put the frame on the screen
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Game());
}
}
感谢@mKorbel即时通讯仍然是相当新的编程和我不能确定链接在“标题到OutOfMemory”是什么是相关的。 卡布局似乎是我正在寻找虽然 – gadu 2013-04-23 08:39:50
您的JButton总是创建一个新的JFrame,与JLabel和图像作为图标,这些形式的对象留在JVM内存中,并增加一个新的JFrame – mKorbel 2013-04-23 08:52:03