我正在写一个俄罗斯方块游戏。当应用程序通过按钮“播放”打开Jlabel时。如何在现有的Jframe内切换到不同的标签(Board)?如何在一个JFrame内切换到JPanel?
像这样,它直接打开游戏..但首先我想使用ButtonPage类来显示一些按钮,然后调用游戏的欢迎屏幕。
public class Tetris extends JFrame {
public Tetris(){
// JFrame Properties
setSize(198, 409);
setResizable(false);
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// ButtonPage buttons = new ButtonPage();
// add(buttons);
// buttons.setOpaque(true);
Board board = new Board(this);
add(board);
board.start();
} // end of constructor
public static void main(String[] args){
Tetris game = new Tetris();
game.setLocationRelativeTo(null);
game.setVisible(true);
game.setLayout(null);
} // end of main
} // end of class
这是ButtonPage类。
public class ButtonPage extends JPanel implements ActionListener{
JButton buttonPLAY = new JButton();
JLabel backgroundImage = new JLabel();
public ButtonPage(){
setLayout(null);
ImageIcon buttonIcon = new ImageIcon(getClass().getResource("PlayButton.png"));
ImageIcon buttonIconHover = new ImageIcon(getClass().getResource("PlayButtonHover.png"));
ImageIcon buttonIconClicked = new ImageIcon(getClass().getResource("PlayButtonClicked.png"));
int buttonHeight = buttonIcon.getIconHeight();
int buttonWidth = buttonIcon.getIconWidth();
buttonPLAY.addActionListener(this);
buttonPLAY.setActionCommand("Play");
buttonPLAY.setIcon(buttonIcon);
buttonPLAY.setRolloverIcon(buttonIconHover);
buttonPLAY.setPressedIcon(buttonIconClicked);
buttonPLAY.setBorderPainted(false);
add(buttonPLAY);
Dimension size2 = getSize();
Dimension size = buttonPLAY.getPreferredSize();
buttonPLAY.setBounds((192 - buttonWidth)/2, 100 ,buttonWidth, buttonHeight);
}// end of constructor
@Override
public void actionPerformed(ActionEvent e) {
if ("Play".equals(e.getActionCommand())) {
Tetris game = new Tetris();
// opens the window in the middle of the screen
game.setLocationRelativeTo(null);
// set the tetris window visible, unless its true - its invisible DUH!
game.setVisible(true);
game.setLayout(null);
}
} // end of actionPerformed
}// end of class
使用actionPerformed方法我可以打开一个新的帧的比赛,但我不知道如何切换面板。
在此先感谢您的任何提示!
不,我只是想证明我能够运行游戏没有问题,但只有当我不使用按钮面板或我使用的面板,但打开一个新的框架.. –
谢谢,CardLayout似乎是正确的做法。然而我仍然有一个问题,就是在我点击play切换到第二个面板之前,游戏开始播放。 –
帮助某人是一种乐趣。什么是'board.start()'? – Aubin