JPanel不工作(PaintComponent)

时间:2015-01-27 09:44:02

标签: java netbeans jpanel

好吧已经好几个月了,因为我在java中没有做任何事情,现在我正在开发一个俄罗斯方块游戏,但是我的jpanel有问题,它没有显示。 班级人物:

package tetris;

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Figure {

int x,y,xVel,yVel,width,heigh;
Image img;
boolean exist;
public Figure(int x,int y){
this.x=x;
this.y=y;
xVel=0;
yVel=2;
this.exist=true;
width=30;
heigh=30;
img= new ImageIcon("Images/Rectangle.png").getImage();
}
  public Figure(){
exist=false;
}
public boolean exists() {
    if(exist==true)
    return true;

    return false;
}

public void move(){
x+=xVel;
y+=yVel;
}
public void draw(Graphics g) {
    g.drawImage(img,x,y,width,heigh,null);
}
}

我想用两个维度类MyMatrix

的数组来做
package tetris;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image; 
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyMatrix extends JPanel   {

int n, m;
Figure[][] matrix;

public MyMatrix(int n, int m) {
   // n and m size of matrix
    setVisible(true);
    this.n = n;
    this.m = m;

    matrix = new Figure[n][m];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            matrix[i][j] = new Figure();

        }
    }
}

public void addFigure(Figure f, int x, int y) {

    matrix[x][y] = f;

}

@Override
public void paintComponent(Graphics g) {
    super.paint(g); //To change body of generated methods, choose Tools | Templates.
    draw(g);
}

public void draw(Graphics g) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j].exists()) {
                matrix[i][j].draw(g);
            }

        }
    }

}
}

我使用了Jframe of netbeans。

public class GUI extends javax.swing.JFrame implements Runnable{

/**
 * Creates new form GUI
 */
MyMatrix m;
public GUI() {
    initComponents();
    m= new MyMatrix(10,10);

    this.add(m);
    m.setLocation(0, 0);
    Figure f= new Figure(10, 10);
   m.addFigure(f,0 ,0);
}
 @Override
public void run() {

    while(true){
        try {
            m.repaint();
            Thread.sleep(5);

        } catch (InterruptedException ex) {
            System.out.println("Error on GUI Thread");
        }
    }
}
}

我试图在绘制方法上执行System.out.println(“Message”),但它不打印任何东西,所以我认为它不是在做repaint()方法,但我不明白为什么。

主要课程:

 package tetris;

 public class Tetris {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    GUI frame= new GUI();
    Thread t= new Thread(frame);
    t.start();
           frame.setVisible(true);
}

 }

0 个答案:

没有答案