我正在使用TicTacToe游戏的图形进行测试,但在点击按钮后更新Canvas时出现问题。当我致电showUpdatedBoard()时,它会创建一个新的画布,但它不会输入paintComponent方法,因此不更新画布。单击按钮后更新画布?
任何帮助,将不胜感激。 谢谢!
(忽略计数和我,他们只是用于测试)
井字游戏类:
public class TicTacToe extends JPanel{
private JFrame mainFrame;
private JPanel mainPanel;
private JPanel canvasPanel;
private JPanel optionsPanel;
private JTextField coord;
private JButton enterCoord;
private int i = 0;
public static void main(String[] args){
TicTacToe tictac = new TicTacToe();
tictac.mainFrame = new JFrame();
tictac.mainFrame.setSize(1600, 900);
tictac.mainFrame.setLocationRelativeTo(null);
tictac.mainFrame.setDefaultCloseOperation(tictac.mainFrame.EXIT_ON_CLOSE);
tictac.mainFrame.setVisible(true);
tictac.makeGUI();
}
public void showUpdatedBoard(){
canvasPanel = new Canvas();
canvasPanel.repaint();
}
private void makeGUI(){
canvasPanel = new Canvas();
mainPanel = new JPanel(new FlowLayout());
mainPanel.add(canvasPanel);
mainFrame.add(mainPanel);
optionsPanel = new JPanel();
coord = new JTextField(4);
enterCoord = new JButton("Enter Co-ordinate");
enterCoord.addActionListener(new enterCoordPress());
optionsPanel.add(coord);
optionsPanel.add(enterCoord);
mainPanel.add(optionsPanel);
}
public class enterCoordPress implements ActionListener{
public void actionPerformed(ActionEvent ev) {
TicTacToe tictac = new TicTacToe();
tictac.showUpdatedBoard();
i++;
coord.setText(String.valueOf(i));
}
}
}
Canvas类:
public class Canvas extends JPanel {
private String[][] Board = new String[3][3];
private int count = 0;
public Canvas(){
this.setPreferredSize(new Dimension(1300, 900));
this.setBackground(Color.WHITE);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println(count);
if(count <= 5){
g.fillRect(0, 0, 1000, 900);
} else {
g.fillRect(0, 0, 120, 546);
}
count++;
}
}
请参阅[*混合重量级和轻量级组件*](http://www.oracle.com/technetwork/articles/java/mixing-components- 433992.html)。 – trashgod