【发布时间】:2011-02-08 12:26:23
【问题描述】:
首先,我是初学者。我正在尝试使用Pieces 的数组制作一个益智游戏。每个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() 的工作原理之前,我无法继续。
所以,请,任何帮助将不胜感激。
【问题讨论】:
-
行 g = jPanel1.getGraphics();在公共 void paintComponent(Graphics g) 中什么都不是,我只是在尝试,但没有成功
-
我建议你创建最小的可运行程序来演示问题并重新发布你的代码。
-
赞成说“但在我完全理解
public void paintComponent(Graphics g)和repaint()的工作原理之前,我不能继续下去。”很多人只是想糊弄过去。
标签: java swing repaint paintcomponent