Images
File: java/Images/Main.java
import java.awt.*;
import javax.swing.*;
/*
* Shows 2 alternative approaches
* both use synchronous loading, cause from local files
*
* cp courses/106/code/dist/kafura/Chapter7/DrawTool/Main/Synch/{blue,red}Ball.gif .
*/
public class Main extends JFrame {
public static void main (String [] args) {
new Main();
}
public Main () {
// Window setup
setLocation (100, 100);
setSize (200, 200);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
// Do it in one shot, no need to remember
content.add (new MyCanvas ());
setVisible (true);
}
}
File: java/Images/MyCanvas.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCanvas extends JComponent {
// Remember it in ivar so can redraw
Image image;
// Ditto, for alternative way
ImageIcon icon;
MyCanvas () {
// Get the image, the easy way
icon = new ImageIcon ("redBall.gif");
// Ditto, the hard way
image = Toolkit.getDefaultToolkit().createImage ("blueBall.gif");
// and blocking wait for it right here
MediaTracker tracker = new MediaTracker (this);
tracker.addImage (image, 0);
try {
tracker.waitForID (0);
} catch (InterruptedException e) {}
}
// This is our draw callback
public void paintComponent (Graphics g) {
// For the easy say
icon.paintIcon (this, g, 100, 100);
// For the hard way
g.drawImage (image, 0, 0, null);
}
}