首先,我是初学者。我正在尝试使用 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()
。
所以,请,任何帮助将不胜感激。