1

The messages that ought to be printed in the printComponent method are not printed. I am having the impression that the paint method is not called. If not, why not?

import java.util.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;

public class Main extends JFrame{
    CustomComponent cc;

    public static void main(String[] args) {
        Main m = new Main();
    }

    public Main(){
        setTitle( "Diverse Testari 7");
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600, 400);

        cc = new CustomComponent();
        cc.setImage("rgbcmy.jpg");

        add(cc);
        pack();
        setVisible( true );
    }
}

class CustomComponent extends JPanel{
    BufferedImage img = null;
    public void setImage( String str ){
    try {
        img = ImageIO.read( new File( str ) );
        System.out.println("SUCCESS!");

    } catch (IOException e) {
        e.printStackTrace();
    }
    }

    @Override
    protected void paintComponent(Graphics g) {
        // TODO Auto-generated method stub
        System.out.println("altceva");
        super.paintComponent(g);
        System.out.println("ceva");
    }
}
4

1 回答 1

2

Add this code in your Main constructor:

new Thread(new Runnable() {
    public void run() {
        repaint();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {}
    }
}).start();

paintComponent will only be called when you repaint();.

Also, NEVER NEVER NEVER use setLayout(null);. See here.

This code will continually repaint the panel, so it will continually call paintComponent. This is good because it will always keep the panel updated. You could also just call repaint(); when you change what's in the panel.

于 2013-01-05T17:00:05.503 回答