You see, the paint() method/event that you have "overidden" will never be "dispatched" in your program, because it is a member function of your Images class which does not extend any graphical components.
To solve this problem, I have added MyCanvas class which overrides the paint() event. So instead of adding the Canvas component to the application window, I added MyCanvas, which will respond to each paint event and draw the image.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
class MyCanvas extends Canvas
{
Image img;
public MyCanvas(Image img)
{
this.img = img;
}
public void paint (Graphics g)
{
if (img != null)
{
g.drawImage(img, 0, 0, 1000, 1000, this);
}
}
public void setImage (Image img){
this.img = img;
}
}
public class Images implements ActionListener, WindowListener
{
Frame fr = new Frame ("Frame");
Label Label1 = new Label("Label1 ");
Button Button1 = new Button("Button 1");
Image Image1;
MyCanvas Canvas1;
FileDialog fd = new FileDialog(fr,"Open", FileDialog.LOAD);
void initialize ()
{
fr.setSize(500,500);
fr.setLocation(300,300);
fr.setBackground(Color.lightGray);
fr.setLayout(new FlowLayout());
fr.add(Label1);
fr.add(Button1);
fr.addWindowListener(this);
Button1.addActionListener(this);
Canvas1 = new MyCanvas(null);
Canvas1.setSize(1000,1000);
fr.add(Canvas1);
fr.show();
}
void imageload ()
{
fd.show();
if(fd.getFile() == null)
{
Label1.setText("You have not chosen any image files yet");
}
else
{
String d = (fd.getDirectory() + fd.getFile());
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image1 = toolkit.getImage(d);
Canvas1.setImage(Image1);
Canvas1.repaint();
}
}
public void windowClosing(WindowEvent e)
{
// Use fr.hide(); for subsequent forms in multi form applications
System.exit(0);
}
public void windowActivated(WindowEvent e)
{
}
public void windowClosed(WindowEvent e)
{
}
public void windowDeactivated(WindowEvent e)
{
}
public void windowDeiconified(WindowEvent e)
{
}
public void windowIconified(WindowEvent e)
{
}
public void windowOpened(WindowEvent e)
{
}
public void actionPerformed(ActionEvent event)
{
Button b = (Button)event.getSource();
if(b == Button1)
{
imageload();
}
}
public static void main(String args[])
{
Images a = new Images();
a.initialize();
}
}