Dessiner sur une BufferedImage
Bonjour,
ds la methode paintComponent(Graphics g) de mon JComponent j'ai cree une BufferedImage et dessine une grille la dessus.
Maintenant je veux quand bougant la souris j'ai une ligne vertical qui se dessine.
J'ai lus pleins de tutoriaux, ds lesquels on dit qu'on peut tres bien dessiner sur une BufferedImage, a condition de recuperer son context graphique avec getGraphics().
Moi ds mon cas, ca marche pas et je comprend pas tres bien pourquoi. Quelqu'un peut-il m'aider?
la c'est le code de paintComponent(Graphics g)
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
...
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
int w = 1500;
int h = 1500;
final int grid_step = 20;
MyPanel.GRIDIMG = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g1 = MyPanel.GRIDIMG.createGraphics();
float[] dashPattern = { 3, 2 };
g1.setStroke(new java.awt.BasicStroke(1, java.awt.BasicStroke.CAP_BUTT, java.awt.BasicStroke.JOIN_MITER, 11, dashPattern, 0));
g1.setColor(Color.WHITE);
g1.fillRect(0, 0, w, h); // fill in background
g1.setColor(Color.LIGHT_GRAY);
//draw horizontal lines
for(int y=h; y>0; y-=grid_step) { g1.drawLine(0, y, w, y); }
//draw vertical lines
for(int x=w; x>0; x-=grid_step) { g1.drawLine(x, 0, x, h); }
g2.drawImage(MyPanel.GRIDIMG, null, 0, 0);
g1.dispose();
g2.dispose();
}
... |
et la celui de public void mouseMoved(MouseEvent e)
Code:
1 2 3 4 5 6 7 8 9 10
|
...
public void mouseMoved(MouseEvent e)
{
Graphics2D g2 = (Graphics2D) MyPanel.GRIDIMG.getGraphics();
g2.setColor(Color.GREEN);
g2.drawLine(e.getX(), 0, e.getX(), this.getHeight());
}
... |
Au fait je precise que la grille se dessine parfaitement mais PAS la ligne verticale.