repaint()不再工作了

时间:2015-05-07 06:42:01

标签: java swing 2d rendering

我正在学习java,我正试图通过JPanel绘制JFrame ......

问题是,我的渲染代码正在运行,但我已经改变了一些东西,现在repaint()方法不再刷新JPanel了......

我在每个方法中都有System.out.println()调用,但我的控制台看起来像这样:

  

渲染   给予   给予   呈现

,当我调用render()方法时。它以前工作.... 无论如何,这是我的代码。

package Graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Surface extends JPanel {

    JFrame frame;
    RandomFrame rf;

    public Surface(JFrame frame) {
        this.frame = frame;
        rf = new RandomFrame(frame.getWidth(), frame.getHeight());
    }

private void draw(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    g2d.setPaint(Color.blue);

    int w = getWidth();
    int h = getHeight();

    g2d.drawImage(rf.getRandom(w, h), null, 0, 0);
    System.out.println("draw");
}

@Override
public void paintComponent(Graphics g) {
    System.out.println("paintComponent");
    super.paintComponents(g);
    draw(g);
}

public void render() {
    System.out.println("render");
    repaint();
}

}

,而RandomFrame返回带有随机数据的BufferedImage。

1 个答案:

答案 0 :(得分:0)

在Surface构造函数中取框,确保将SurfacePanel添加到框架中。例如

public Surface(JFrame frame) { this.frame = frame; frame.setContentPane(this); // add this line rf = new RandomFrame(frame.getWidth(), frame.getHeight()); }