1 / 93

Lecture 8

Lecture 8. CS203. Common Recurrence Relations. Comparing Common Growth Functions. Logarithmic time. Constant time. Linear time. Log-linear time. Quadratic time. Cubic time. Exponential time. Comparing Common Growth Functions. .jar files.

kevork
Télécharger la présentation

Lecture 8

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 8 CS203

  2. Common Recurrence Relations

  3. Comparing Common Growth Functions Logarithmic time Constant time Linear time Log-linear time Quadratic time Cubic time Exponential time

  4. Comparing Common Growth Functions

  5. .jar files • .jar files are used for distributing Java applications and libraries. • The file format is .zip, but the extension .jar identifies them as Java Archives • They contain bytecode (.class files), any other files from the application or library (like images or audio files), and can also contain source code • The JDK contains command line tools for making jar files, but this is easier to do with Eclipse • Jar files may be executable, meaning that they are configured to launch the main() of some class contained in the jar

  6. .jar files

  7. .jar files

  8. Using Libraries • Java has a very strong culture of open-source software • Students, professors, programming hobbyists, and developers who choose to give back to the profession make many projects available for free • This allows you to use functionality you lack the time or expertise to code • It also requires a slightly different set of skills than those you use when you write your own code form scratch. Programming becomes an exercise in hacking other people's ideas so they fit together to get the results you want. You will seldom find that the programmers of the libraries you use thought their work out the same way you would have. • Quality control is nonexistent and malware is probably sometimes spread this way! • You will learn several other ways to get libraries and integrate them into your projects, but here is the simple way

  9. Using Libraries • Find the website for the library you want and download it. • If you have the choice to get the bytecode alone or with the source included, get the version that includes the source • You will usually need to unzip or untar the library. The free software 7-Zip can untar, but avoid installing the junkware that comes with 7-Zip. • The result will include one or more .jar files. Often there is also documentation, tutorials, and other material as well. • Right click on the project name and choose "Build Path/Configure Build Path", then "Add External JARs", then find the Jar you need to add. • The library should now appear under "Referenced Libraries" in your project

  10. Using Libraries

  11. JFreeChart • JFreeChart is a very widely used free library for creating graphs in Java. • If the demo below is not enough, google JFreeChart bar graph (or whatever else you need to look up) for tutorials and discussions, especially on StackOverflow.com • Download JFreeChart from http://www.jfree.org/jfreechart/download.html

  12. Using Libraries package charts; import java.awt.Color; import java.awt.Dimension; import java.awt.GradientPaint; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class BarChartDemo extends ApplicationFrame { public BarChartDemo(final String title) { super(title); final CategoryDataset dataset = createDataset(); final JFreeChart chart = createChart(dataset); final ChartPanelchartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(500, 270)); setContentPane(chartPanel); }

  13. private CategoryDatasetcreateDataset() { // row keys... final String series1 = "Widgets"; // column keys... final String category1 = "Category 1"; final String category2 = "Category 2"; final String category3 = "Category 3"; final String category4 = "Category 4"; final String category5 = "Category 5"; // create the dataset... final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(1.0, series1, category1); dataset.addValue(4.0, series1, category2); dataset.addValue(3.0, series1, category3); dataset.addValue(5.0, series1, category4); dataset.addValue(5.0, series1, category5); return dataset; } private JFreeChartcreateChart(final CategoryDataset dataset) { // create the chart... final JFreeChart chart = ChartFactory.createBarChart("Bar Chart Demo", // chart

  14. // title "Category", // domain axis label "Value", // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); // set the background color for the chart... chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customisation... final CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); // set the range axis to display integers only... final NumberAxisrangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // disable bar outlines... final BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setDrawBarOutline(false); // set up gradient paints for series... final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, Color.lightGray); final GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, Color.lightGray);

  15. final GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, Color.lightGray); renderer.setSeriesPaint(0, gp0); renderer.setSeriesPaint(1, gp1); renderer.setSeriesPaint(2, gp2); final CategoryAxisdomainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions .createUpRotationLabelPositions(Math.PI / 6.0)); return chart; } public static void main(final String[] args) { final BarChartDemo demo = new BarChartDemo("Bar Chart Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } }

  16. PDFBox PDFBox is a library for extracting text from pdfs Get the "Standalone binary" at https://pdfbox.apache.org/downloads.html As is typical for this type of library, it is not well documented. If the demo below is not enough, check Eclipse's context-sensitive help or look for comments on StackOverflow.

  17. PDFBox package pdftograph; import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; public class PDFBoxDemo { public void readPDF(File f) { PDDocument p; PDFTextStripper strip; String text = null; try { p = PDDocument.load(f); strip = new PDFTextStripper(); text = strip.getText(p); } catch (IOException e) { e.printStackTrace(); } System.out.println(text); } public static void main(String[] args){ PDFBoxDemo reader = new PDFBoxDemo(); reader.readPDF(new File("Dracula_T.pdf")); } }

  18. Using Libraries • See why it's so important to adhere to conventions for things like method name capitalization?

  19. GUIs • This week's lab will require using Swing. The next few slides are a review of CS202 material on Swing. • Swing is likely to be displaced over the next few years in favor of a newer framework called JavaFX, but the basic concepts used Swing remain similar to those involved in many other GUI frameworks

  20. GUIs • Swing apps are based on components that are placed inside frames. • A component might be another frame, an image, a check box, button, etc. A frame is a component that is the outer container for the GUI. You can move the whole frame on the screen, resize it, etc. • The usual frame used in Swing is the JFrame. • Components, including JFrame, are created by instantiating objects of component classes. • Many common Swing components are listed at http://www.oracle.com/technetwork/java/architecture-142923.html. This site also has a discussion of the general architecture and principles of Swing • I'll use many components without introducing them first; the basic nature of the component is always obvious. • You may eventually use GUI builder toolkits to put components together, but you have to understand how GUI programming works before you can take short cuts. Write all your GUI code in this course yourself, not with a GUI builder.

  21. Layout Managers • Java’s layout managers automatically map your user interface on all window systems so that GUIs can be platform-independent and display-independent. • The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. • Layout managers are set in containers using the setLayout(LayoutManager) method in a container. • Several types of layout managers: • FlowLayout • GridLayout • BorderLayout • There are also several others slides on Layout Managers are from Liang, Introduction To Java Programming

  22. Layout Managers • FlowLayout • Starts at a corner (top left by default but can be changed), add content to the end of the row, then start the next row, etc • GridLayout • Orderly rows and columns: • BorderLayout: • divides the container into five areas: East, South, West, North, and Center. • There are also several other LayoutManagers • For more information on LayoutManagers, check http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

  23. JPanel • JPanel is a container you can add to a frame and use to hold almost any kind of components. • Separating parts of your GUI into JPanels and then working with the JPanels allows more flexibility than just putting components directly into the JFrame. • I don’t have a lot to say about JPanel: I'm introducing it here because the next few demos use it

  24. Layout Managers // adapted from http://www.java2s.com/Code/Java/Swing-JFC/GridLayoutDemo.htm package guidemo; import java.awt.Color; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class GridLayoutDemo { private JComponent createComponent(String s) { JLabel l = new JLabel(s); l.setBorder(BorderFactory .createMatteBorder(5, 5, 5, 5, Color.DARK_GRAY)); l.setHorizontalAlignment(JLabel.CENTER); return l; } public static void main(String[] args){ GridLayoutDemo g = new GridLayoutDemo(); g.createGUI(); }

  25. Listeners and Event Handlers • Our programs so far have asked for input at times directed by the code, then handled the input when given. • GUI programs must handle events that are user-directed and may occur at any time. • GUI actions raise Events. These are objects of subclasses of the class EventObject • Event Handlers specify which events the program will notice and what to do when they occur • In Java, these are called "ActionListeners"

  26. Anonymous Classes With GUIs Add an ActionListener to the button The class is created right here in this method call. It has no name, but it implements ActionListener applyButton.addActionListener(new ActionListener() { ActionListener requires only an ActionPerformed method public void actionPerformed(ActionEvent e){ that takes the event as an argument String command = group.getSelection().getActionCommand(); // Check the selection if (command.equals("Left to right")) { compsToExperiment.setComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT); } else { compsToExperiment.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); } // update the experiment layout compsToExperiment.validate(); compsToExperiment.repaint(); } end of the actionPerformed method of the anonymous class }); semicolon is the end of the whole statement close paren is the end of the argument list for addActionListener() Curly brace is the end of the anonymous class

  27. JLabel and MouseListener Demo The MouseListener interface requires several methods that implement mouse actions for a Swing component. The following demo implements this interface and also shows some ways to set the appearance of a JLabel. This demo will be useful when you are preparing Lab 8.

  28. JLabel and MouseListener Demo package guidemo; import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JLabel; public class LabelAndMouseListenerDemo { private JFrame frame; private JLabel label; private void createAndShowGUI() { frame = new JFrame("MouseListener Demo"); label = new JLabel("Unclicked!"); label.setBackground(Color.green); label.setOpaque(true); label.setHorizontalAlignment(0); label.setPreferredSize(new Dimension(150, 150)); label.addMouseListener(new MouseListener() { boolean clicked = false;

  29. JLabel and MouseListener Demo @Override public void mouseClicked(MouseEvent arg0) { if (clicked == true) { clicked = false; label.setText("Unclicked!"); } else { clicked = true; label.setText("Clicked!"); } } @Override public void mouseEntered(MouseEvent arg0) { label.setBackground(Color.red); } @Override public void mouseExited(MouseEvent arg0) { label.setBackground(Color.green); } @Override public void mousePressed(MouseEvent arg0) { label.setBackground(Color.blue); }

  30. JLabel and MouseListener Demo @Override public void mouseReleased(MouseEvent arg0) { label.setBackground(Color.green); } }); frame.add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { LabelAndMouseListenerDemo gui = new LabelAndMouseListenerDemo(); gui.createAndShowGUI(); }; }

  31. Tuning GUI Appearance There are at least two good ways to find details on how to adjust the appearance of Swing GUIs: Google a phrase like "JLabel text alignment" and see what you find. Oracle documentation is comprehensive, but StackOverflow.com usually has the most practical answers Use Eclipse's context-sensitive help:

  32. Listener Classes • Anonymous ActionListeners are 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

  33. 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(); }; }

  34. 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()); } }

  35. 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()); } } }

  36. 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*

  37. 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(); } }

  38. 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.

  39. // 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); } }); } }

  40. 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.

  41. 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

  42. Images 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.

  43. 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.

  44. 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); } });

  45. 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); } });

  46. 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. */

  47. 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(); } }

  48. 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(); } }

  49. 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; }

  50. Binary Trees A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree is a hierarchical structure. It is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree.

More Related