0

我正在写一个俄罗斯方块游戏。当应用程序启动带有“播放”按钮的 Jlabel 时,将打开。如何在现有 Jframe 中切换到不同的标签(Board)?

像这样它直接打开游戏。但首先我想使用 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 方法,我可以在新框架中打开游戏,但我不知道如何切换面板。

提前感谢您的任何提示!

4

2 回答 2

0

俄罗斯方块是从 main 中提取出来的,下面的行来自 actionPerformed():

Tetris game = new Tetris();

实例化第二个俄罗斯方块,这真的是你想要的吗?

要将多个面板添加到一个框架,一次只能看到一个,请使用CardLayout

于 2012-10-26T21:56:11.990 回答
0

您是否尝试过卡片布局?

http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

于 2012-10-26T21:56:38.497 回答