Import java.awt. *; import java.awt.event. *; Import java.awt.image. *; import java.io. *; import javax.swing. *;
public class ImageViewer {public static void main (String [] args) {JFrame frame = new ImageViewerFrame (); frame.setTitle ( "ImageViewer"); frame.setSize (300, 400); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); Frame.show ();}}
class ImageViewerFrame extends JFrame {public ImageViewerFrame () {// set up menu bar JMenuBar menuBar = new JMenuBar (); setJMenuBar (menuBar); JMenu menu = new JMenu ( "File"); menuBar.add (menu); JMenuItem openItem = new JMenuItem ( "Open"); menu.add (openItem); openItem.addActionListener (new FileOpenListener ()); JMenuItem exitItem = new JMenuItem ( "Exit"); menu.add (exitItem); exitItem.addActionListener (new ActionListener ( ) {Public void actionPerformed (ActionEvent Event)
{System.exit (0);}}); // Use a label to display the images label = new jlabel (); container contentpane = getContentPane (); contentpane.add (label);}
private class FileOpenListener implements ActionListener {public void actionPerformed (ActionEvent evt) {// set up file chooser JFileChooser chooser = new JFileChooser (); chooser.setCurrentDirectory ( "." new File ());
// Accept all files ending with .gif chooser.setfilefilter (new javax.swing.filechooser.filefilter () {public boolean accept (file f) {return f.getname (). TOLOWERCASE () .endswith (". gif") || f.isDirectory ();} public String getDescription () {return "GIF Images";}}); // show file chooser dialog int r = chooser.showOpenDialog (ImageViewerFrame.this); // if image file accepted, Set it as icon of the label if (r == jfilechooser.Approve_option) {string name = chooser.getSelectedFile (). getPath (); label.seticon (Name);}}}
The Private Jlabel Label;} Writsed on the book of Core Java, the original written is a lot of errors. Ha ha ~ Later, many are many problems in grammar. And the program is hard to see. . Later, I have revised many times. Of course, I look at Shu Lu to modify. After all, it is an initiator. Just intend to take advantage of such a source code to deepen your understanding. It feels very cool after success. I am very happy. Oh, it is very important to develop a good habit style ~