import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; public class App extends JFrame implements ActionListener { public static void main(String args[]) { new App(); } public App() { /* Set layout for this containter */ this.getContentPane().setLayout( new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); /* Add Menu Bar to this JFrame, add Menu: "File" */ JMenuBar menubar = new JMenuBar(); this.setJMenuBar(menubar); JMenu filemenu = new JMenu("File"); menubar.add(filemenu); /* Add Menu Item: "Open" */ open_menu_item = new JMenuItem("Open"); open_menu_item.addActionListener(this); filemenu.add(open_menu_item); /* Add Seperating Space between Menu Item for it to look nice*/ filemenu.addSeparator(); /* Add Menu Item: "Exit" */ file_menu_item = new JMenuItem("Exit"); file_menu_item.addActionListener(this); filemenu.add(file_menu_item); /* Create JLabel */ label = new JLabel("No Image Loaded"); this.getContentPane().add(label); //Add to pane /* Create button and add to pane*/ button = new JButton("Clear"); button.addActionListener(this); this.getContentPane().add(button); /* Standard Finishing calls */ this.pack(); //Tell JFrame to layout its components this.setVisible(true); //Make JFrame visibile this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tell JFrame to exit the program when the window is closed } /* Handle Events for this JFrame's Components */ public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setIcon(null); label.setText("No Image Loaded"); this.pack(); } else if (e.getSource() == open_menu_item) { try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { Icon image = new ImageIcon( chooser.getSelectedFile().getName()); label.setIcon(image); label.setText(null); this.pack(); } } catch (Exception except) { JOptionPane.showMessageDialog(this, except.toString()); } } else if (e.getSource() == file_menu_item) { System.exit(0); } } JButton button; JLabel label; JMenuItem open_menu_item; JMenuItem file_menu_item; }