1 / 44

Lecture 11

Lecture 11. CS 202 Fall 2013. ActionEvent Methods. ActionEvent contains many methods you can use to get information about events. import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JButton;

arav
Télécharger la présentation

Lecture 11

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 11 CS 202 Fall 2013

  2. ActionEvent Methods ActionEvent contains many methods you can use to get information about events. import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; public class EventInfoGUI { JFrame frame; JButton button; private void createAndShowGUI() { frame = new JFrame("Event Info Demo"); button = new JButton("Click Me"); frame.add(button, BorderLayout.CENTER); button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent event) { System.out.println("Command: " + event.getActionCommand()); System.out.println("ID: " + event.getID()); System.out.println("Modifiers: " + event.getModifiers()); System.out.println("Source: " + event.getSource()); System.out.println("Date and Time: " + new Date(event.getWhen())); System.out.println("Parameter String: " + event.paramString()); System.out.println("Class: " + event.getClass()); }}); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { EventInfoGUI gui = new EventInfoGUI(); gui.createAndShowGUI(); }; } See http://docs.oracle.com/javase/6/docs/api/java/awt/event/ActionEvent.html for a complete list

  3. ActionEvent Methods package guidemo; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class SquareGrid { JFrame theFrame; JButton[][] buttons; int rowCount = 5; int colCount = 5; JPanel panel; private void createAndShowGui(){ theFrame = new JFrame ("grid"); buttons = new JButton[rowCount][colCount]; panel = new JPanel(); panel.setLayout(new GridLayout(rowCount, colCount)); for(int rowCounter = 0; rowCounter < rowCount; rowCounter++) for(int colCounter = 0; colCounter < colCount; colCounter++){ final JButton j = new JButton("not clicked"); j.addActionListener(new ActionListener(){ boolean clicked = false; @Override public void actionPerformed(ActionEvent event) { if(clicked == false) clicked = true; else clicked = false; if(clicked) j.setText("clicked"); else j.setText("not clicked"); } }); buttons[rowCounter][colCounter] = j; panel.add(j); } theFrame.add(panel); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); theFrame.pack(); theFrame.setVisible(true); } public static void main(String[] args){ SquareGrid h = new SquareGrid(); h.createAndShowGui(); } }

  4. ActionEvent Methods for(int rowCounter = 0; rowCounter < rowCount; rowCounter++) for(int colCounter = 0; colCounter < colCount; colCounter++){ final JButton j = new JButton("Click Me!"); j.setBackground(Color.RED); j.addActionListener(new ActionListener(){ boolean clicked = false; @Override public void actionPerformed(ActionEvent event) { if(clicked == false) clicked = true; else clicked = false; if(clicked) j.setBackground(Color.GREEN); else j.setBackground(Color.RED); System.out.println("Source: " + event.getSource()); } }); buttons[rowCounter][colCounter] = j; panel.add(j); } To make a component accessible inside an anonymous ActionListener attached to it, make the component final

  5. Listener Classes • Recall the code from the Celsius Converter, which used an anonymous class to implement ActionListener • This is a convenient solution if the listener is simple and you only need to use it in one place • However, it is hard to read and can’t be reused • For more complex ActionListeners, it is better to code non-anonymous classes that implement ActionListener, either separately or as inner classes

  6. Listener Classes • EventInfoGUI2 with separate ClickListener class import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; public class EventInfoGUI2 { JFrame frame; JButton button; private void createAndShowGUI() { frame = new JFrame("Event Info Demo"); button = new JButton("Click Me"); frame.add(button, BorderLayout.CENTER); button.addActionListener(new EventInfoClickListener()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { EventInfoGUI2 gui = new EventInfoGUI2(); gui.createAndShowGUI(); }; }

  7. Listener Classes • ClickListener class import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; public class EventInfoClickListener implements ActionListener{ @Override public void actionPerformed(ActionEvent event) { System.out.println("Command: " + event.getActionCommand()); System.out.println("ID: " + event.getID()); System.out.println("Modifiers: " + event.getModifiers()); System.out.println("Source: " + event.getSource()); System.out.println("Date and Time: " + new Date(event.getWhen())); System.out.println("Parameter String: " + event.paramString()); System.out.println("Class: " + event.getClass()); } }

  8. Listener Classes • It is also common to use an inner class that implements a Listener interface: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; public class EventInfoGUI3 { JFrame frame; JButton button; private void createAndShowGUI() { frame = new JFrame("Event Info Demo"); button = new JButton("Click Me"); frame.add(button, BorderLayout.CENTER); button.addActionListener(new EventInfoClickListener2()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { EventInfoGUI3 gui = new EventInfoGUI3(); gui.createAndShowGUI(); }; private class EventInfoClickListener2 implements ActionListener{ @Override public void actionPerformed(ActionEvent event) { System.out.println("Command: " + event.getActionCommand()); System.out.println("ID: " + event.getID()); System.out.println("Modifiers: " + event.getModifiers()); System.out.println("Source: " + event.getSource()); System.out.println("Date and Time: " + new Date(event.getWhen())); System.out.println("Parameter String: " + event.paramString()); System.out.println("Class: " + event.getClass()); } } }

  9. JTable • JTable is a JComponent that displays a table • Contents come from a Table Model • The most straightforward form of Table Model uses a one-dimensional array of Strings for column names and a two-dimensional array of Objects for data. • This can be invisible to the programmer, who just sends the parameters to the JTable constructor • Since your data is usually in a list, not a two dimensional array, you have to write a method to generate the array. • There are ways to provide more sophisticated data models for JTable, but they are *very complicated*

  10. JTable // http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SimpleTableDemoProject/src/components/SimpleTableDemo.java package menudemo; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class SimpleTableDemo extends JPanel { public SimpleTableDemo() { super(new GridLayout(1, 0)); String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" }; final Object[][] data = { { "Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false) }, { "John", "Doe", "Rowing", new Integer(3), new Boolean(true) }, { "Sue", "Black", "Knitting", new Integer(2), new Boolean(false) }, { "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) }, { "Joe", "Brown", "Pool", new Integer(10), new Boolean(false) } }; JTable table = setUpTable(data, columnNames); // Create the scroll pane and add the table to it. JScrollPanescrollPane = new JScrollPane(table); // Add the scroll pane to this panel. add(scrollPane); } private JTablesetUpTable(Object[][] data, String[] columnNames){ JTable table = new JTable(data, columnNames); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); table.setAutoCreateRowSorter(true); return table; } private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame("SimpleTableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. SimpleTableDemonewContentPane = new SimpleTableDemo(); newContentPane.setOpaque(true); // content panes must be opaque frame.setContentPane(newContentPane); // Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { createAndShowGUI(); } }

  11. Menus • JMenus are placed in JMenuBarsand contain JMenuItems • JMenuItems trigger events that can be handled with ActionListeners • setMnemonic() provides hotkeys as an alternative to using the mouse; very useful for accessibility.

  12. // http://zetcode.com/tutorials/javaswingtutorial/menusandtoolbars/ package menudemo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; public class Example extends JFrame { public Example() { initUI(); } public final void initUI() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenuItem eMenuItem = new JMenuItem("Exit"); eMenuItem.setMnemonic(KeyEvent.VK_E); eMenuItem.setToolTipText("Exit application"); eMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); file.add(eMenuItem); menubar.add(file); setJMenuBar(menubar); setTitle("Simple menu"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setVisible(true); } }); } }

  13. JFileChooser • JFileChooser is a dialog box that lets the user choose a file to open, save as , etc. It will look familiar when you see it. • By default, JFileChooser starts in the users' default directory (the one you see if you open Windows Explorer). Other starting directories can be specified. • JFileChooser returns a selected file or an array of selected files • JFileChooser() creates JFileChooser instance using user’s default directory. • JFileChooser(File currentDirectory) creates JFileChooser instance using a given directory. • setMultiSelectionEnabled(true) allows multiple file selections. This may or may not be appropriate for your task.

  14. Example • Example allows user to choose one or more files, using a method from a separate FileDumper class to print the contents of the files(s) to output. • Test it with text files only, or you will get strange results

  15. package menudemo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class JFileChooserDemo { final JFrame frame; final FileDumper f; public JFileChooserDemo() { f = new FileDumper(); frame = new JFrame("JFileChooser Demo"); initUI(); } public final void initUI() { JMenuBar menubar = setUpMenus(); setUpFrame(menubar); }

  16. public JMenuBar setUpMenus() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); // instance variables are only visible inside anonymous classes if they // are final final JFileChooser fc = new JFileChooser(); // allow multiple selections. Don't use with Save As... ! fc.setMultiSelectionEnabled(true); JMenuItem fMenuItem = new JMenuItem("Open"); fMenuItem.setMnemonic(KeyEvent.VK_O); fMenuItem.setToolTipText("Open A File"); fMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { int retVal = fc.showOpenDialog(frame); if (retVal == JFileChooser.APPROVE_OPTION) { File[] selectedfiles = fc.getSelectedFiles(); for (int i = 0; i < selectedfiles.length; i++) { f.readFileToSystemOut(selectedfiles[i]); } } } }); JMenuItem eMenuItem = new JMenuItem("Exit"); eMenuItem.setMnemonic(KeyEvent.VK_E); eMenuItem.setToolTipText("Exit application"); eMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); file.add(fMenuItem); file.add(eMenuItem); menubar.add(file); return menubar; }

  17. private void setUpFrame(JMenuBar menubar) { frame.setJMenuBar(menubar); frame.setTitle("Simple menu"); frame.setSize(300, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { JFileChooserDemo ex = new JFileChooserDemo(); } }

  18. FileDumper package menudemo; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileDumper { public void readFileToSystemOut(File f){ Scanner reader; try { System.out.println(f.getName()); reader = new Scanner(f); //... Loop as long as there are input lines. String line = null; while (reader.hasNextLine()) { line = reader.nextLine(); System.out.println(line); } //... Close reader reader.close(); System.out.println(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

  19. Look And Feel • Swing apps, like those using many other GUI frameworks, can use a variety of "Look and Feel" styles that control various graphic aspects of the GUI. • Available L and Fs vary between platforms • Set L and F in the first line of main: • UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

  20. Look And Feel package guidemo; // from java2s: http://www.java2s.com/Code/Java/Swing-JFC/SimplelookandfeelExample.htm import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class SimpleLookAndFeelDemo extends JPanel { static JFrame frame; static String metal = "Metal"; static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel"; static String motif = "Motif"; static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";

  21. Look And Feel static String windows = "Windows"; static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; JRadioButton metalButton, motifButton, windowsButton; public SimpleLookAndFeelDemo() { JButton button = new JButton("Hello, world"); button.setMnemonic('h'); // for looks only; button does nada metalButton = new JRadioButton(metal); metalButton.setMnemonic('o'); metalButton.setActionCommand(metalClassName); motifButton = new JRadioButton(motif); motifButton.setMnemonic('m'); motifButton.setActionCommand(motifClassName); windowsButton = new JRadioButton(windows); windowsButton.setMnemonic('w'); windowsButton.setActionCommand(windowsClassName); ButtonGroup group = new ButtonGroup(); group.add(metalButton); group.add(motifButton); group.add(windowsButton);

  22. Look And Feel RadioListener myListener = new RadioListener(); metalButton.addActionListener(myListener); motifButton.addActionListener(myListener); windowsButton.addActionListener(myListener); add(button); add(metalButton); add(motifButton); add(windowsButton); } class RadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { String lnfName = e.getActionCommand(); try { UIManager.setLookAndFeel(lnfName); SwingUtilities.updateComponentTreeUI(frame); frame.pack(); } catch (Exception exc) { JRadioButton button = (JRadioButton) e.getSource(); button.setEnabled(false); updateState(); System.err.println("Could not load LookAndFeel: " + lnfName); } } }

  23. Look And Feel public void updateState() { String lnfName = UIManager.getLookAndFeel().getClass().getName(); if (lnfName.indexOf(metal) >= 0) { metalButton.setSelected(true); } else if (lnfName.indexOf(windows) >= 0) { windowsButton.setSelected(true); } else if (lnfName.indexOf(motif) >= 0) { motifButton.setSelected(true); } else { System.err.println("SimpleExample is using an unknown L&F: " + lnfName); } } public static void main(String s[]) { SimpleLookAndFeelDemo panel = new SimpleLookAndFeelDemo(); frame = new JFrame("SimpleExample"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add("Center", panel); frame.pack(); frame.setVisible(true); panel.updateState(); } }

  24. More On Layout Managers • Border Layout can also be used with these areas: • PAGE_START • PAGE_END • LINE_START • LINE_END • CENTER • It is easy to think of them as corresponding to North, South, West, East, and Center on a map.

  25. Instanceof • The next layout manager demo uses Java's instanceof operator, which determines whether an object is an instance of a particular class • The syntax of instanceof may be counterintuitive; the keyword does not use camel case and there are no parentheses around the class name • The next slide shows a simple demo of instanceof

  26. Instanceof package demos; public class Demo { Object myObject; public void setMyObject(Object o) { myObject = o; } public Object getMyObject() { return myObject; } public static void main(String[] args) { Demo demo = new Demo(); String newObject = new String("John"); demo.setMyObject(newObject); Object o = demo.getMyObject(); if (o instanceof String) System.out.println("\"" + o + "\"" + " is a String!"); else System.out.println("not a String!"); Object arch = new Archimedes(); demo.setMyObject(arch); Object o2 = demo.getMyObject(); if (o2 instanceof String) System.out.println("\"" + 02 + "\"" + " is a String!"); else System.out.println(o2 + " is not a String!"); } }

  27. More On Layout Managers package menudemo; // http://docs.oracle.com/javase/tutorial/uiswing/examples/layout/BorderLayoutDemoProject/src/layout/BorderLayoutDemo.java import javax.swing.*; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; public class BorderLayoutDemo { public static booleanRIGHT_TO_LEFT = false; public static void addComponentsToPane(Container pane) { if (!(pane.getLayout() instanceofBorderLayout)) { pane.add(new JLabel("Container doesn't use BorderLayout!")); return; } if (RIGHT_TO_LEFT) { pane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT); } JButton button = new JButton("Button 1 (PAGE_START)"); pane.add(button, BorderLayout.PAGE_START); //Make the center component big, since that's the //typical usage of BorderLayout. button = new JButton("Button 2 (CENTER)"); button.setPreferredSize(new Dimension(200, 100)); pane.add(button, BorderLayout.CENTER);

  28. More On Layout Managers button = new JButton("Button 3 (LINE_START)"); pane.add(button, BorderLayout.LINE_START); button = new JButton("Long-Named Button 4 (PAGE_END)"); pane.add(button, BorderLayout.PAGE_END); button = new JButton("5 (LINE_END)"); pane.add(button, BorderLayout.LINE_END); } private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("BorderLayoutDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. addComponentsToPane(frame.getContentPane()); //Use the content pane's default BorderLayout. No need for //setLayout(new BorderLayout()); //Display the window. frame.pack(); frame.setVisible(true); }

  29. More On Layout Managers public static void main(String[] args) { /* Use an appropriate Look and Feel */ try { //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } /* Turn off metal's use bold fonts */ UIManager.put("swing.boldMetal", Boolean.FALSE); //Schedule a job for the event dispatch thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

  30. More On Layout Managers • The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. • When using the CardLayout class, let the user choose between the components by using a combo box, menu, etc. http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

  31. More On Layout Managers package menudemo; // http://docs.oracle.com/javase/tutorial/uiswing/examples/layout/CardLayoutDemoProject/src/layout/CardLayoutDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutDemo implements ItemListener { JPanel cards; //a panel that uses CardLayout final static String BUTTONPANEL = "Card with JButtons"; final static String TEXTPANEL = "Card with JTextField"; public void addComponentToPane(Container pane) { //Put the JComboBox in a JPanel to get a nicer look. JPanel comboBoxPane = new JPanel(); //use FlowLayout String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL }; JComboBox cb = new JComboBox(comboBoxItems); cb.setEditable(false); cb.addItemListener(this); comboBoxPane.add(cb);

  32. More On Layout Managers //Create the "cards". JPanel card1 = new JPanel(); card1.add(new JButton("Button 1")); card1.add(new JButton("Button 2")); card1.add(new JButton("Button 3")); JPanel card2 = new JPanel(); card2.add(new JTextField("TextField", 20)); //Create the panel that contains the "cards". cards = new JPanel(new CardLayout()); cards.add(card1, BUTTONPANEL); cards.add(card2, TEXTPANEL); pane.add(comboBoxPane, BorderLayout.PAGE_START); pane.add(cards, BorderLayout.CENTER); } public void itemStateChanged(ItemEvent evt) { CardLayout cl = (CardLayout)(cards.getLayout()); System.out.println(evt.getItem()); System.out.println(evt.getSource()); cl.show(cards, (String)evt.getItem()); }

  33. More On Layout Managers private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("CardLayoutDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. CardLayoutDemo demo = new CardLayoutDemo(); demo.addComponentToPane(frame.getContentPane()); //Display the window. frame.pack(); frame.setVisible(true); }

  34. More On Layout Managers public static void main(String[] args) { /* Use an appropriate Look and Feel */ try { //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } /* Turn off metal's use of bold fonts */ UIManager.put("swing.boldMetal", Boolean.FALSE); createAndShowGUI(); } }

  35. Images in Swing • BufferedImage reads and writes image files • ImageIcon displays an image. It was originally used to create icons but is typically used for all images. • ImageIcons are typically added to Jlabels which are then placed in the frame

  36. // adapted from http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-a-jpanel // paste the image file directly to your project, not into src or any other folder within it package menudemo; import java.awt.BorderLayout; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class ImageDemo { JFrame frame; JPanel panel; JLabel picLabel; BufferedImage myPicture; public ImageDemo() { frame = new JFrame(); myPicture = null; try { File f = new File("godzilla.jpg"); myPicture = ImageIO.read(f); ImageIcon i = new ImageIcon(myPicture); picLabel = new JLabel(i); } catch (IOException e) { e.printStackTrace(); } setUpFrame(); } private void setUpFrame(){ frame = new JFrame("Show an image"); panel = new JPanel(); panel.add(picLabel); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { ImageDemo i = new ImageDemo(); } }

  37. Images More sophisticated image demo, from http://alvinalexander.com/java/jwarehouse/netbeans-src/usersguide/demosrc/examples/imageviewer/ImageFrame.java.shtml The author of this demo used a GUI builder which left some annotations that are not relevant to us. I may not have deleted them all.

  38. Images This example uses several new (to us) components. Note that if you mouse-hover over a class name in code in Eclipse, you see a description of the class from the class' Javadoc.

  39. Images package week10; /** This class is an entry point of the simple image viewer. * It creates and shows the main application frame. */ public class ImageViewer extends javax.swing.JFrame { /** Image Viewer constructor. * It initializes all GUI components [menu bar, menu items, desktop pane, etc.]. */ public ImageViewer() { initComponents(); pack(); setBounds( 100, 100, 400, 400 ); } private void initComponents() { desktop = new javax.swing.JDesktopPane(); mainMenuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); openMenuItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); exitMenuItem = new javax.swing.JMenuItem(); setTitle("Image Viewer"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } });

  40. Images getAccessibleContext().setAccessibleName("Image Viewer Frame"); getContentPane().add(desktop, java.awt.BorderLayout.CENTER); desktop.getAccessibleContext().setAccessibleName("Image Desktop"); desktop.getAccessibleContext().setAccessibleDescription("Image desktop"); fileMenu.setMnemonic('f'); fileMenu.setText("File"); openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openMenuItem.setMnemonic('o'); openMenuItem.setText("Open"); openMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); openMenuItem.getAccessibleContext().setAccessibleName("Open Menu Item"); openMenuItem.getAccessibleContext().setAccessibleDescription("Open menu item."); fileMenu.add(jSeparator1); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } });

  41. Images fileMenu.add(exitMenuItem); exitMenuItem.getAccessibleContext().setAccessibleName("Exit Menu Item"); exitMenuItem.getAccessibleContext().setAccessibleDescription("Exit menu item."); mainMenuBar.add(fileMenu); fileMenu.getAccessibleContext().setAccessibleName("File Menu"); fileMenu.getAccessibleContext().setAccessibleDescription("File menu."); setJMenuBar(mainMenuBar); mainMenuBar.getAccessibleContext().setAccessibleName("Main Menu Bar"); mainMenuBar.getAccessibleContext().setAccessibleDescription("Main menu bar."); } /** This method is called when File -> Exit menu item is invoked. * It closes the application. * @param evt ActionEvent instance passed from actionPerformed event. */ private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) { System.exit( 0 ); } /** This method is called when File -> Open menu item is invoked. * It displays a dialog to choose the image file to be opened and displayed. * @param evt ActionEvent instance passed from actionPerformed event. */

  42. Images private void openMenuItemActionPerformed(java.awt.event.ActionEventevt) { javax.swing.JFileChooser chooser = new javax.swing.JFileChooser(); chooser.addChoosableFileFilter(new ImageFileFilter()); int option = chooser.showOpenDialog(this); if (option == javax.swing.JFileChooser.APPROVE_OPTION) { java.io.File file = chooser.getSelectedFile(); if (file == null) return; ImageFrameifr = new ImageFrame(file.getAbsolutePath()); desktop.add(ifr, javax.swing.JLayeredPane.DEFAULT_LAYER); ifr.setVisible( true ); ifr.setSize(200, 200); ifr.setLocation(0, 0); } } /** This method is called when the application frame is closed. * @paramevtWindowEvent instance passed from windowClosing event. */ private void exitForm(java.awt.event.WindowEventevt) { System.exit(0); } /** Define custom file filter for acceptable image files. */ private static class ImageFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(java.io.File file) { if (file == null) return false; return file.isDirectory() || file.getName().toLowerCase().endsWith(".gif") || file.getName().toLowerCase().endsWith(".jpg"); } public String getDescription() { return "Image files (*.gif, *.jpg)"; } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDesktopPane desktop; private javax.swing.JMenuItemexitMenuItem; private javax.swing.JMenufileMenu; private javax.swing.JSeparator jSeparator1; private javax.swing.JMenuBarmainMenuBar; private javax.swing.JMenuItemopenMenuItem; // End of variables declaration//GEN-END:variables /** Starts the application. * @paramargs Application arguments. */ public static void main(String args[]) { new ImageViewer().show(); } }

  43. Images public String getDescription() { return "Image files (*.gif, *.jpg)"; } } // Variables declaration private javax.swing.JDesktopPane desktop; private javax.swing.JMenuItemexitMenuItem; private javax.swing.JMenufileMenu; private javax.swing.JSeparator jSeparator1; private javax.swing.JMenuBarmainMenuBar; private javax.swing.JMenuItemopenMenuItem; // End of variables declaration//GEN-END:variables /** Starts the application. * @paramargs Application arguments. */ public static void main(String args[]) { new ImageViewer().show(); } }

  44. package week10; /** Instances of this class create internal frames to display given images. */ public class ImageFrame extends javax.swing.JInternalFrame { /** ImageFrame constructor. * It creates new internal frame containing the given image and displays it. */ public ImageFrame(String imageName ) { initComponents(); setTitle(imageName); imageLabel.setIcon(new javax.swing.ImageIcon(imageName) ); } /** This method is called from within the constructor to * initialize the form. */ private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); imageLabel = new javax.swing.JLabel(); setClosable(true); setIconifiable(true); setResizable(true); getAccessibleContext().setAccessibleName("Image Internal Frame"); getAccessibleContext().setAccessibleDescription("Image internal frame."); jScrollPane1.setViewportView(imageLabel); imageLabel.getAccessibleContext().setAccessibleName("Image Label"); imageLabel.getAccessibleContext().setAccessibleDescription("Image label."); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); } // Variables declaration private javax.swing.JLabel imageLabel; private javax.swing.JScrollPane jScrollPane1; }

More Related