Image doesn't display properly
Hello everyone,
I am very new to Java programming, or any programming for that matter.
I have been playing with getting images to display in an application
when an action is performed, but I have been experiencing problems.
When I click the button the image doesn't display. If I click the
button a second time the image displays. Could anyone tell me how I
could resolve this?
Here is a very simple version of my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleImage extends JFrame implements ActionListener{
Image exampleImage;
JButton btnExample;
public SimpleImage( ) {
super("Image Example");
// Get the image from the file
btnExample = new JButton("Click Me");
Container pane = getContentPane( );
FlowLayout flow = new FlowLayout();
pane.setLayout(flow);
pane.add(btnExample);
// Set up the frame features
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//event handler
btnExample.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== btnExample){
exampleImage =
Toolkit.getDefaultToolkit().getImage("happyface.jpg");
Graphics draw = getGraphics();
draw.drawImage(exampleImage, 100, 175, this);
}
}
public static void main(String[ ] args) {
SimpleImage frame = new SimpleImage( );
}
}