我正在使用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