1

首先,我是初学者。我正在尝试使用 s 数组制作益智游戏Piece。每个Piece代表一个从 1 到 9 的数字。我正在尝试使用 绘制paintComponent(Graphics g),但是当我调用该repaint()方法时,什么也没有发生。没有错误,所以一定有一些我不知道的地方。

我正在使用 NetBeans。我创建了一个新的桌面应用程序,然后添加了一个JPanel和一个JButton.

这是我的代码:

public class PuzzleGame2View extends FrameView {

public Piece pieces[][];

Drawing outer = new Drawing();

public PuzzleGame2View(SingleFrameApplication app) {

super(app);

initComponents();
//more code that netbeans automatically wrote......

public class Drawing extends JFrame implements MouseListener{
    public void paintComponent(Graphics g ){
        g = jPanel1.getGraphics();
        super.paintComponents(g);

        for (int i = 0; i < pieces.length; i++) {
            for (int j = 0; j < pieces.length; j++) {
                if (pieces[i][j].getText()!=null) {
                    g.setColor(Color.red);
                     g.fillRect(i*100, j*100, 100, 100);
                     g.setColor(Color.BLACK);
                     g.drawString(pieces[i][j].getText(), i*100 + 50, j*100 + 20);

                }
            }
        }
    }

    public void makePieces(){
    pieces = new Piece[3][3];
    for (int i = 0; i < pieces.length; i++) {
        for (int j = 0; j < pieces.length; j++) {
            if (i == 2 && j == 2){
                pieces[i][j] = new Piece(j, j, null);
            }
             else

            pieces[i][j] = new Piece(j, j, "" + (i*3+j+1) );
        }
    }
}

repaint()当我单击按钮时,我试图调用该方法。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
makePieces();
outer.repaint();
}                  

这是课程Piece

package puzzlegame2;

public class Piece {
private int row,count;
private String text;

public Piece(int row, int count, String text) {
    this.row = row;
    this.count = count;
    this.text = text;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}
}

这只是第一步;有好多事情要做。public void paintComponent(Graphics g)但在我完全理解如何工作之前,我不能继续下去repaint()

所以,请,任何帮助将不胜感激。

4

2 回答 2

2

尝试覆盖该paint()方法而不是paintComponents(). repaint()向 发送呼叫paint()

编辑:在任何情况下你都应该改变的一件事是你正在覆盖paintComponent()你的JFrame. 相反,您应该在您的中覆盖此方法,JPanel然后将新面板设置为 JFrame 的内容面板。然后repaint()在面板上调用。

于 2011-02-08T12:34:36.117 回答
1

revalidate()在重绘之前尝试调用

于 2011-02-08T13:31:37.983 回答