2D-Grafik BufferedImage Hintergrund immer schwarz

  • Themenstarter Themenstarter Graf Iker
  • Beginndatum Beginndatum
G

Graf Iker

Gast
Hallo allerseits! Ich versuche mich seit einigen Tagen an der 2D Ausgabe in Java und will mir dazu jetzt erstmal ein Fenster erstellen, in welchem ich ein JPanel platziere, auf welches wiederum ich ein BufferedImage zeichnen will. Das funktioniert auch bis auf die Tatsache, dass egal welche Hintergrundfarbe ich im BufferedImage einstelle, ich auf dem Panel immer schwarz zu sehen bekomme. Die Paintfarbe passt.

Hier der Code meiner Klasse:

Java:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class gWindow extends JFrame {
    
    customCanvas p_canvas;
    BufferedImage img;
    
    public gWindow () {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.initWindow();
        this.setVisible(true);
    }
    
    protected final void initWindow () {
        Container content = this.getContentPane();
        
        img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
        
        Graphics2D g2 = img.createGraphics();
        g2.setPaint(Color.RED);
        g2.setBackground(Color.WHITE);
        g2.drawLine(0,0,150,150);

        p_canvas = new customCanvas();
        p_canvas.setPreferredSize(new Dimension(500,500));
        p_canvas.setBackground(Color.WHITE);
        
        p_canvas.paintComponent(g2);
        
        content.add(p_canvas);
        
        this.pack();
    }

    
    public class customCanvas extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(img, 0, 0, 300, 300, 0, 0, 300, 300, null);
        }
    }

    public static void main(String[] args) {
        gWindow myWindow = new gWindow();
    }
}

Sieht jemand das Problem? Bitte um Hilfestellung und danke schonmal!
 
Siehe:
http://download.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#setBackground(java.awt.Color) hat gesagt.:
Setting the background color in the Graphics2D context only affects the subsequent clearRect calls and not the background color of the Component
rufe also nach
Code:
g2.setBackground(Color.WHITE);
-->
Code:
g2.clearRect(0, 0, img.getWidth(), img.getHeight());
auf z.B.
 

Zurück
Oben