public class ImageViewer{ public static void main(String[] args){ JFrame frame = new ImageViewerFrame(); frame.setTitle("ImageViewer"); int w = 320, h =400 ; Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setBounds((int)((ScreenSize.width-w)/2),(int)((ScreenSize.height-h)/2),w,h); frame.setSize(w,h); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } }
class ImageViewerFrame extends JFrame{ public ImageViewerFrame(){ //set menu 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 iamges label = new JLabel(); Container contentPane = getContentPane(); contentPane.add(label,"Center"); }
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";