Im trying to get to grips wth java 2d graphics
Ive basically got a JPanel with a backgrounfd image in it like so:
public MapFrame(Plotting pl){
this.pl =pl;
this.setPreferredSize(new Dimension(984,884));
this.setBorder(BorderFactory.createEtchedBorder());
try {
getFileImage("stars.jpg");
}
catch (Exception ex) {
}
this.addMouseMotionListener(this);
this.addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, null);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(0x756b48));
g2d.drawLine(0,0,0,100);
}
private void getFileImage(String filePath) throws InterruptedException, IOException {
FileInputStream in = new FileInputStream(filePath);
byte [] b=new byte[in.available()];
in.read(b);
in.close();
bg=Toolkit.getDefaultToolkit().createImage(b);
MediaTracker mt=new MediaTracker(this);
mt.addImage(bg,0);
mt.waitForAll();
}
In paint component I want to overlay small images 12x12 pixels in a loop at various xy points that ill get from some xml.
Cant seem to get an i开发者_如何转开发mage to overlay over my first one
Im a bit lost here and v rusty
Any help would b gr8
public void paintComponent(Graphics g) {
g.drawImage(bg, 0, 0, null);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(0x756b48));
g2d.drawLine(0,0,0,100);
for(SomeXMLObject o : yourXMLSource) {
g.drawImage(yourImage, o.x, o.y, null);
}
}
Please specify clearer how your XML is parsed, if you already did that. Then, you'd also need to load the "12x12" image. SomeXMLObject
is a structure containing x
and y
variables, extracted from your XML.
If you call g.drawImage(...) after the background: it will be painted after the background, and thus overlay. Be sure you load a png-24 image, to enable translucency-areas, if you'd want that.
If you want to paint an image at various locations, it is as simple as calling Graphics.drawImage(Image, int, int, ImageObserver)
multiple times for different coordinates (as shown in the previous answer).
As for loading images, I'd recommend using one of the ImageIO.read
methods instead of doing it yourself.
You probably want to use use the ImageIO library to load your image. If you have an image filename all you need to do to load it is
BufferedImage bimg = ImageIO.load(new File(filename));
That's a little easier then the code you have above.
After that, like other people said you can use the g.drawImage(bimg,x,y,this);
to actually draw the images.
Oh Dear
Id formatted the filenames of my resources wrong
what a donkey I am
All good advice I think though guys
精彩评论