Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package algo; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.RefineryUtilities; /** * * @author Google */ class PlotBar extends JFrame { public PlotBar(String applicationTitle, String chartTitle) throws FileNotFoundException, IOException { super(applicationTitle); JFreeChart barChart = ChartFactory.createBarChart(chartTitle, "Algorithms", "Execution Time(ms)", createDataset(), PlotOrientation.VERTICAL, true, true, false); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); ChartPanel chartPanel = new ChartPanel(barChart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 420)); setContentPane(chartPanel); } double fileReadTime(String fileName) throws FileNotFoundException, IOException { File file = new File(fileName); FileInputStream fis = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; fis.read(data); fis.close(); String str = new String(data, "UTF-8"); return Double.parseDouble((str.isEmpty()) ? "0.0" : str); } private CategoryDataset createDataset() throws FileNotFoundException, IOException { final String BinarySearchMergeSort = "Binary"; final String InterpolationSearchMerge = "Interpolation"; final String NormalMergeSort = "Normal"; final String TanSort = "TAN"; final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(fileReadTime("time_binary_search_merge_sort.txt") * 1000, BinarySearchMergeSort, BinarySearchMergeSort); dataset.addValue(fileReadTime("time_interpolation_search_merge_sort.txt") * 1000, InterpolationSearchMerge, InterpolationSearchMerge); dataset.addValue(fileReadTime("time_normal_merge_sort.txt") * 1000, NormalMergeSort, NormalMergeSort); dataset.addValue(fileReadTime("time_tan_sor2.txt") * 1000, TanSort, TanSort); return dataset; } } public class Algorithm extends javax.swing.JFrame implements ActionListener { JComboBox cb; /** * Creates new form Algorithm * * @throws java.io.IOException */ public Algorithm() throws IOException { setTitle("Algorithm Simulation"); initComponents(); BufferedImage wPic = ImageIO.read(ClassLoader.getSystemResource("algo/res/bubbles.jpg")); imageLabel.setIcon(new ImageIcon(wPic)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { comboAlgo = new javax.swing.JComboBox(); buttonOk = new javax.swing.JButton(); imageLabel = new javax.swing.JLabel(); labelExecutionTime = new javax.swing.JLabel(); labelExecutionOutput = new javax.swing.JLabel(); labelExecution = new javax.swing.JLabel(); labelExecutionTimeElapsed = new javax.swing.JLabel(); btnPlot = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(450, 450)); comboAlgo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Algorithm", "Binary Search Merge Sort", "Interpolation Search Merge Sort", "Normal Merge Sort", "Tan Sort" })); comboAlgo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comboAlgoActionPerformed(evt); } }); buttonOk.setText("Run"); buttonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonOkActionPerformed(evt); } }); labelExecutionTime.setText("Time Elapsed :"); labelExecutionTime.setToolTipText(""); labelExecution.setText("Execution :"); btnPlot.setText("Plot"); btnPlot.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPlotActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelExecution, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(41, 41, 41).addComponent(labelExecutionOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelExecutionTime, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelExecutionTimeElapsed, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(comboAlgo, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonOk) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnPlot).addGap(0, 0, Short.MAX_VALUE))))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(18, 18, 18).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(comboAlgo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonOk).addComponent(btnPlot)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(labelExecution, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE) .addComponent(labelExecutionOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(labelExecutionTime, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE) .addComponent(labelExecutionTimeElapsed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void comboAlgoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboAlgoActionPerformed // TODO add your handling code here: // cb = (JComboBox) evt.getSource(); // String comboSelected = (String) cb.getSelectedItem(); // System.out.println(comboSelected); /// For bubbles.jpg image switch (comboAlgo.getSelectedIndex()) { /// For Heap.jpg image case 0: try { BufferedImage wPic = ImageIO.read(ClassLoader.getSystemResource("algo/res/bubbles.jpg")); //JLabel wIcon = new JLabel(new ImageIcon(original)); labelExecutionOutput.setText(""); imageLabel.setIcon(new ImageIcon(wPic)); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; /// For merge.jpg case 1: try { BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/heap.jpg")); //JLabel wIcon = new JLabel(new ImageIcon(original)); labelExecutionOutput.setText(""); //double widthFactor = .4; //double heightFactor = .4; // imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor))); imageLabel.setIcon(new ImageIcon(original)); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; /// For quick.jpg case 2: try { BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/merge.jpg")); //double widthFactor = .3; //double heightFactor = .38; labelExecutionOutput.setText(""); // imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor))); imageLabel.setIcon(new ImageIcon(original)); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; case 3: try { BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/quick.png")); double widthFactor = .8; double heightFactor = .9; labelExecutionOutput.setText(""); imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor))); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; case 4: try { BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/chess.png")); //double widthFactor = .5; //double heightFactor = .5; labelExecutionOutput.setText(""); //imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor))); imageLabel.setIcon(new ImageIcon(original)); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; default: break; } }//GEN-LAST:event_comboAlgoActionPerformed private BufferedImage bufferResize(BufferedImage original, double widthFactor, double heightFactor) { // original image width & height int w, h; w = original.getHeight(); h = original.getWidth(); // System.out.println(original.getHeight()); // System.out.println(original.getWidth()); // new width & height calculated by multiplying factor int newWidth = new Double(original.getWidth() * widthFactor).intValue(); int newHeight = new Double(original.getWidth() * heightFactor).intValue(); // new resized image BufferedImage buffResized = new BufferedImage(newWidth, newHeight, original.getType()); Graphics2D g = buffResized.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, w, h, null); g.dispose(); return buffResized; } private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed BufferedReader br; /// For bubbles.jpg image switch (comboAlgo.getSelectedIndex()) { /// For Bubble.jpg image case 0: JOptionPane.showMessageDialog(null, "Select Algorithm", "Algorithm Selection", JOptionPane.INFORMATION_MESSAGE); // labelExecutionOutput.setText("Bubble Sort"); // try { // System.out.println(comboAlgo.getSelectedItem().toString()); // Runtime rt = Runtime.getRuntime(); // Process pr = rt.exec(new String[]{"cmd.exe", // "/c", // "start", // "BubbleSort.exe" // }); // // } catch (IOException ex) { // Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); // } break; /// For merge.jpg case 1: labelExecutionOutput.setText("Binary Search Merge Sort"); try { System.out.println(comboAlgo.getSelectedItem().toString()); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "Binary_search_merge_sort.exe" }); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } try { String fileName = "time_binary_search_merge_sort.txt"; br = new BufferedReader(new FileReader(fileName)); File file = new File(fileName); Thread thread; thread = new Thread() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } if (file.exists()) { try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // System.out.println(line); labelExecutionTimeElapsed.setText(line.concat(" s")); br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } } } }; thread.start(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; /// For quick.jpg case 2: labelExecutionOutput.setText("Interpolation Merge Sort"); try { System.out.println(comboAlgo.getSelectedItem().toString()); Runtime rt = Runtime.getRuntime(); Process pr = rt .exec(new String[] { "cmd.exe", "/c", "start", "interpolation_search_merge_sort.exe" }); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } try { String fileName = "time_interpolation_search_merge_sort.txt"; br = new BufferedReader(new FileReader(fileName)); File file = new File(fileName); Thread thread; thread = new Thread() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } if (file.exists()) { try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // System.out.println(line); labelExecutionTimeElapsed.setText(line.concat(" s")); br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } } } }; thread.start(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; case 3: labelExecutionOutput.setText("Normal Merge Sort"); try { System.out.println(comboAlgo.getSelectedItem().toString()); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "normal_merge_sort.exe" }); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } try { String fileName = "time_normal_merge_sort.txt"; br = new BufferedReader(new FileReader(fileName)); File file = new File(fileName); Thread thread; thread = new Thread() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } if (file.exists()) { try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // System.out.println(line); labelExecutionTimeElapsed.setText(line.concat(" s")); br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } } } }; thread.start(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; case 4: labelExecutionOutput.setText("TAN Sort"); try { System.out.println(comboAlgo.getSelectedItem().toString()); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "TAN_SOR2.exe" }); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } // time_tan_sor2.txt try { String fileName = "time_tan_sor2.txt"; br = new BufferedReader(new FileReader(fileName)); File file = new File(fileName); Thread thread; thread = new Thread() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } if (file.exists()) { try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // System.out.println(line); labelExecutionTimeElapsed.setText(line.concat(" s")); br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } } } }; thread.start(); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } break; default: break; } }//GEN-LAST:event_buttonOkActionPerformed private void btnPlotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlotActionPerformed try { // TODO add your handling code here: // final JFXPanel fxPanel = new JFXPanel(); // panelPlot.add(fxPanel); // // Platform.runLater(new Runnable() { // @Override // public void run() { // initFX(fxPanel); // } // }); PlotBar chart = new PlotBar("Algorithm Execution Plot", "Comparison of Sorting Algorithms"); chart.pack(); RefineryUtilities.centerFrameOnScreen(chart); chart.setVisible(true); } catch (FileNotFoundException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnPlotActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Algorithm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Algorithm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Algorithm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Algorithm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new Algorithm().setVisible(true); } catch (IOException ex) { Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex); } } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnPlot; private javax.swing.JButton buttonOk; private javax.swing.JComboBox comboAlgo; private javax.swing.JLabel imageLabel; private javax.swing.JLabel labelExecution; private javax.swing.JLabel labelExecutionOutput; private javax.swing.JLabel labelExecutionTime; private javax.swing.JLabel labelExecutionTimeElapsed; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }