单击按钮后更新画布?

时间:2014-02-25 19:20:24

标签: java swing canvas

我正在测试使用TicTacToe游戏的图形,但是在点击按钮后更新Canvas时遇到问题。当我调用 showUpdatedBoard()时,它会从 Canvas 类创建一个新的Canvas,但它不会进入 paintComponent 方法,因此不会更新画布。

任何帮助将不胜感激。 谢谢!

(忽略计数和我,他们只是为了测试)

TicTacToe课程:

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));
    }
}
}

画布类:

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++;
}

}

2 个答案:

答案 0 :(得分:0)

尝试使用

canvasPanel.update(canvasPanel.getGraphics());

而不是

canvasPanel.repaint();

答案 1 :(得分:0)

基本上,当您使用new时,您正在创建一个全新的组件实例,一个与您之前创建的任何关系没有任何关系的实例,以及一个没有出现在屏幕上的实例... / p>

canvasPanel = new Canvas();
canvasPanel.repaint();

什么都不做因为Swing很聪明,知道你的组件没有被实现(连接到本地对等并放在屏幕上),所以它从来没有为任何绘画安排它,这将浪费时间这样做。

相反,您需要以某种方式更新canvasPanel的状态,以反映您想要显示的更改,只需调用repaint

同样适合您的actionPerformed方法,不要创建TicTacToe的新实例,因为它不是实际在屏幕上的组件实例...