Smile.java

Download Smile.java

 1: // Smile.java - A Java runnable Jar that displays a GIF graphic.
 2: // To create the Jar, compile Smile.java as normal, then:
 3: //   jar -cfe Smile.jar Smile Smile*.class Mona.gif
 4: // To run your Jar, either double-click the Jar or:
 5: //   java -jar Smile.jar
 6: //
 7: // Written 11/2017 by Wayne Pollock, Tampa FL USA.
 8: 
 9: import java.awt.*;
10: import java.awt.event.*;
11: import java.io.IOException;
12: import javax.swing.JOptionPane;
13: import javax.imageio.ImageIO;
14: 
15: public class Smile extends Frame {
16:     // TODO: make image name a command line argument:
17:     private static final String IMAGE_NAME = "Mona.gif";
18:     private static Image pic;
19: 
20:     public static void main ( String[] args ) {
21:         // Load the image from the same place as Smile.class:
22:         try {
23:            pic = ImageIO.read( Smile.class.getResource( IMAGE_NAME ) );
24:         } catch ( IOException e ) {
25:             JOptionPane.showMessageDialog( null, "Cannot read \"" +
26:             IMAGE_NAME + "\"!" );
27:             return; // Abort program
28:         }
29: 
30:         Frame me = new Smile();
31:         me.setTitle( IMAGE_NAME );
32:         // Set Frame size to the picture's dimensions, plus extra for the
33:         // titlebar height and Frame border (determined by trial and error):
34:         me.setSize( pic.getWidth( null ) + 40, pic.getHeight( null ) + 60 );
35:         me.setLocationRelativeTo( null );  // Center frame on screen
36:         me.setBackground( Color.CYAN );
37: 
38:         // Make closing the window exit the program:
39:         me.addWindowListener(
40:         new WindowAdapter() {
41:             public void windowClosing( WindowEvent e ) {
42:                 System.exit( 0 );
43:             }
44:         });
45: 
46:         me.setVisible( true );
47:     }
48: 
49:     public void paint ( Graphics g ) {
50:         // Draw the picture below the titlebar, centered in the Frame:
51:         g.drawImage( pic, 20, 40, null );
52: 
53:         // Draw a red 1-pixel frame around the picture:
54:         g.setColor( Color.RED );
55:         int picWidth = pic.getWidth( null );
56:         int picHeight = pic.getHeight( null );
57:         g.drawRect( 19, 39, picWidth+1, picHeight+1 );
58:     }
59: }