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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
package swing.painting;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage im;
private List<Shape> shapes;
private Color lineColor = Color.yellow.brighter().brighter();
public ImagePanel(BufferedImage im) {
super();
this.im = im;
shapes = new ArrayList<Shape>();
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
int verticalPosition = e.getPoint().y;
shapes.add(new Line2D.Float(0,verticalPosition,getWidth(),verticalPosition));
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(im.getWidth(),im.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(im,0,0,null);
//Creation d'un contexte graphique temporaire
Graphics2D g2d = (Graphics2D) g.create();
g2d.setPaint(lineColor);
for(Shape s : shapes) {
g2d.draw(s);
}
//finalisation du contexte temporaire
g2d.dispose();
}
public static void main(String[] args) {
try {
BufferedImage im = ImageIO.read(ImagePanel.class.getResource("/res/img/bubble/bubble.png"));
ImagePanel p = new ImagePanel(im);
JFrame f = new JFrame();
f.add(p);
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
Partager