Java 单击按钮时打开表单

Java Swing open form on button click

我正在 java Swing(第一次使用 java swing)开发纸牌翻牌游戏。我正在使用 netbeans,我有一个像新游戏这样的菜单。我希望当用户单击新游戏按钮时游戏开始。但是我不知道如何做到这一点,比如当用户点击按钮时,然后在事件处理动作功能中,是这样的吗?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
  JFrame myframe = new JFrame();
  //and the game functionality here

}                                        

如果您想在单击按钮时打开一个新的 window,那么您做对了。在您的示例代码中,您需要使新框架可见。

public class NewGame {

public static void main(String[] args) {
    JFrame frame = new JFrame("Start up frame");
    JButton newGameButton = new JButton("New Game");
    frame.setLayout(new FlowLayout());
    frame.add(newGameButton);
    frame.setVisible(true);

    newGameButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFrame newGameWindow = new JFrame("A new game!");
            newGameWindow.setVisible(true);
            newGameWindow.add(new JLabel("Customize your game ui in the new window!"));
            newGameWindow.pack();
        }
    });
    frame.pack();
}
}