java - JFrame 重绘/重载

标签 java swing

我在开始新 session 时遇到困难。当我使用菜单选项新游戏时,我得到一个新实例——实际上,我只想用一个新实例替换当前实例。我已经尝试了很多不同的东西,但仍然无法解决......

这是我的代码:

package tictactoe;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TicTacToe2 extends JFrame implements ActionListener {

char[][] game = new char[3][3];
JButton[][] buttons = new JButton[3][3]; 

JButton menuItem      = new JButton();   
JMenu     menu        = new JMenu  ("TicTacToe");
JMenuItem newgame     = new JMenuItem("Start New Game"), 
          exit        = new JMenuItem("Exit"); 

TicTacToe2()
{
    super("Tic Tac Toe");
    setSize(500, 600);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    setLayout( new BorderLayout());

    JPanel northPanel= new JPanel();
    northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));  
    add("North", northPanel);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(3,3, 4, 4));
    add("Center", buttonPanel);
    Font font = new Font("Serif", Font.BOLD, 32);

    for (int row=0; row < game.length; row++)
    {
        for (int col =0; col < game[row].length; col++)
        {
            game[row][col] = ' ';
            JButton b = new JButton(" ");
            b.setFont(font);
            b.setBackground(Color.green);
            b.addActionListener(this);
            buttons[row][col] = b;
            buttonPanel.add(b);
        }
    } 

    menu.add(newgame);  
    menu.add(exit);
    newgame.addActionListener(this); 
    exit.addActionListener(this); 

    JMenuBar bar = new JMenuBar( ); 
    bar.add(menu);  
    setJMenuBar(bar); 

} 
public void actionPerformed(ActionEvent e) {
    Object  menusource = e.getSource();   
    if(menusource ==  newgame){ 
        new TicTacToe2();   
    }else if(menusource ==  exit){
        System.exit(0);
    }  
} 
public static void main(String[] args) {
    TicTacToe2 ttt = new TicTacToe2();

}
}

最佳答案

每次通过“新游戏”菜单时,您都在创建一个新实例:

        new TicTacToe2();   

如果您只想重置实例,请编写一个将游戏状态设置为初始状态的 reset() 方法。

关于java - JFrame 重绘/重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101900/

相关文章:

java - 无法向位于其他类的 `paintComponent()` 方法提供鼠标坐标

java - 在按下/选择时操作 JToggleButton 的 ImageIcon

Java 可运行问题

java - JLex 是否包含 yymore 函数?

java - 发生内存不足错误

java - 空指针异常 : Overriding constructor calling method of Base class in Derived class

java - 检测 Swing 中的(框架+组件)焦点

java - 如果我们将 SessionScoped bean 注入(inject)到 Stateless bean 中,如果没有 HTTP session 会发生什么?

java - 我应该如何将 JLabel 从 JFrame 中的一个 JPanel 拖动到同一 JFrame 中另一个 JPanel 中的 JTextField 上?

java - 在让 Swing 组件被垃圾收集之前,我是否需要释放它们?