Tuesday, 2 June 2015

How to Read data from console without IO package in Java?

       

import java.util.*;
class a
{
public static void main(String args[])throws Exception
{Scanner snr= new Scanner(System.in);

String s=snr.nextLine();
char arr[]=s.toCharArray();

System.out.println(arr);





}
}

 

MiniBrowser in Java.

       

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;

// The Simple Web Browser.
public class MiniBrowser extends JFrame
        
        implements HyperlinkListener {
    // These are the buttons for iterating through the page list.
    private JButton backButton, forwardButton;
    
    // Page location text field.
    private JTextField locationTextField;
    
    // Editor pane for displaying pages.
    private JEditorPane displayEditorPane;
    
    // Browser's list of pages that have been visited.
    private ArrayList pageList = new ArrayList();
    
    // Constructor for Mini Web Browser.
    public MiniBrowser() {
        // Set application title.
        super("Mini Browser");
        
        // Set window size.
        setSize(640, 480);
        
        // Handle closing events.
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                actionExit();
            }
        });
        
        // Set up file menu.
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        JMenuItem fileExitMenuItem = new JMenuItem("Exit",
                KeyEvent.VK_X);
        fileExitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionExit();
            }
        });
        fileMenu.add(fileExitMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
        
        // Set up button panel.
        JPanel buttonPanel = new JPanel();
        backButton = new JButton("< Back");
        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionBack();
            }
        });
        backButton.setEnabled(false);
        buttonPanel.add(backButton);
        forwardButton = new JButton("Forward >");
        forwardButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionForward();
            }
        });
        forwardButton.setEnabled(false);
        buttonPanel.add(forwardButton);
        locationTextField = new JTextField(35);
        locationTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    actionGo();
                }
            }
        });
        buttonPanel.add(locationTextField);
        JButton goButton = new JButton("GO");
        goButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionGo();
            }
        });
        buttonPanel.add(goButton);
        
        // Set up page display.
        displayEditorPane = new JEditorPane();
        displayEditorPane.setContentType("text/html");
       displayEditorPane.setEditable(false);
        displayEditorPane.addHyperlinkListener(this);
        
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(buttonPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(displayEditorPane),
                BorderLayout.CENTER);
    }
    
    // Exit this program.
    private void actionExit() {
        System.exit(0);
    }
    
    // Go back to the page viewed before the current page.
    private void actionBack() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex - 1)), false);
        } catch (Exception e) {}
    }
    
    // Go forward to the page viewed after the current page.
    private void actionForward() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex + 1)), false);
        } catch (Exception e) {}
    }
    
    // Load and show the page specified in the location text field.
    private void actionGo() {
        URL verifiedUrl = verifyUrl(locationTextField.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("Invalid URL");
        }
    }
    
    // Show dialog box with error message.
    private void showError(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage,
                "Error", JOptionPane.ERROR_MESSAGE);
    }
    
    // Verify URL format.
    private URL verifyUrl(String url) {
        // Only allow HTTP URLs.
        if (!url.toLowerCase().startsWith("http://"))
            return null;
        
        // Verify format of URL.
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }
        
        return verifiedUrl;
    }
    
  /* Show the specified page and add it to
     the page list if specified. */
    private void showPage(URL pageUrl, boolean addToList) {
        // Show hour glass cursor while crawling is under way.
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        try {
            // Get URL of page currently being displayed.
            URL currentUrl = displayEditorPane.getPage();
            
            // Load and display specified page.
            displayEditorPane.setPage(pageUrl);
            
            // Get URL of new page being displayed.
            URL newUrl = displayEditorPane.getPage();
            
            // Add page to list if specified.
            if (addToList) {
                int listSize = pageList.size();
                if (listSize > 0) {
                    int pageIndex =
                            pageList.indexOf(currentUrl.toString());
                    if (pageIndex < listSize - 1) {
                        for (int i = listSize - 1; i > pageIndex; i--) {
                            pageList.remove(i);
                        }
                    }
                }
                pageList.add(newUrl.toString());
            }
            
            // Update location text field with URL of current page.
            locationTextField.setText(newUrl.toString());
            
            // Update buttons based on the page being displayed.
            updateButtons();
        } catch (Exception e) {
            // Show error messsage.
            showError("Unable to load page");
        } finally {
            // Return to default cursor.
            setCursor(Cursor.getDefaultCursor());
        }
    }
    
  /* Update back and forward buttons based on
     the page being displayed. */
    private void updateButtons() {
        if (pageList.size() < 2) {
            backButton.setEnabled(false);
            forwardButton.setEnabled(false);
        } else {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            backButton.setEnabled(pageIndex > 0);
            forwardButton.setEnabled(
                    pageIndex < (pageList.size() - 1));
        }
    }
    
    // Handle hyperlink's being clicked.
    public void hyperlinkUpdate(HyperlinkEvent event) {
        HyperlinkEvent.EventType eventType = event.getEventType();
        if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
            if (event instanceof HTMLFrameHyperlinkEvent) {
                HTMLFrameHyperlinkEvent linkEvent =
                        (HTMLFrameHyperlinkEvent) event;
                HTMLDocument document =
                        (HTMLDocument) displayEditorPane.getDocument();
                document.processHTMLFrameHyperlinkEvent(linkEvent);
            } else {
                showPage(event.getURL(), true);
            }
        }
    }
    
    // Run the Mini Browser.
    public static void main(String[] args) {
        MiniBrowser browser = new MiniBrowser();
        browser.show();
    }
}
 

How to Execute a Java Program by Cprogram?

it can be use as a .exe luncher of awt swing program..
it work in windows only!!
compile this by javac document.java

       
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Document extends JFrame implements ActionListener
{
private JTextArea ta;
private int count;
private JMenuBar menuBar;
private JMenu fileM,editM,viewM;
private JScrollPane scpane;
private JMenuItem exitI,cutI,copyI,pasteI,selectI,saveI,loadI,statusI;
private String pad;
private JToolBar toolBar;
public Document()
{
    super("Document");
    setSize(600, 600);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container pane = getContentPane();
    pane.setLayout(new BorderLayout());

    count = 0;
    pad = " ";
    ta = new JTextArea(); //textarea
    menuBar = new JMenuBar(); //menubar
    fileM = new JMenu("File"); //file menu
    editM = new JMenu("Edit"); //edit menu
    viewM = new JMenu("View"); //edit menu
    scpane = new JScrollPane(ta); //scrollpane  and add textarea to scrollpane
    exitI = new JMenuItem("Exit");
    cutI = new JMenuItem("Cut");
    copyI = new JMenuItem("Copy");
    pasteI = new JMenuItem("Paste");
    selectI = new JMenuItem("Select All"); //menuitems
    saveI = new JMenuItem("Save"); //menuitems
    loadI = new JMenuItem("Load"); //menuitems
    statusI = new JMenuItem("Status"); //menuitems
    toolBar = new JToolBar();

    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);

    setJMenuBar(menuBar);
    menuBar.add(fileM);
    menuBar.add(editM);
    menuBar.add(viewM);

    fileM.add(saveI);
    fileM.add(loadI);
    fileM.add(exitI);

    editM.add(cutI);
    editM.add(copyI);
    editM.add(pasteI);        
    editM.add(selectI);

    viewM.add(statusI);

    saveI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    loadI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
    cutI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
    copyI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
    pasteI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
    selectI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));

    pane.add(scpane,BorderLayout.CENTER);
    pane.add(toolBar,BorderLayout.SOUTH);

    saveI.addActionListener(this);
    loadI.addActionListener(this);
    exitI.addActionListener(this);
    cutI.addActionListener(this);
    copyI.addActionListener(this);
    pasteI.addActionListener(this);
    selectI.addActionListener(this);
    statusI.addActionListener(this);

    setVisible(true);
}
public void actionPerformed(ActionEvent e) 
{
    JMenuItem choice = (JMenuItem) e.getSource();
    if (choice == saveI)
    {
        //not yet implmented
    }
    else if (choice == exitI)
        System.exit(0);
    else if (choice == cutI)
    {
        pad = ta.getSelectedText();
        ta.replaceRange("", ta.getSelectionStart(), ta.getSelectionEnd());
    }
    else if (choice == copyI)
        pad = ta.getSelectedText();
    else if (choice == pasteI)
        ta.insert(pad, ta.getCaretPosition());
    else if (choice == selectI)
        ta.selectAll();
    else if (e.getSource() == statusI)
    {
        //not yet implmented
    }
}
public static void main(String[] args) 
{
    new Document();
}
}

 

Compile this C program by gcc compiler in windows.
Run .exe file Which will work as a luncher of Document.class.

       
#include stdio.h
main()
{
system("java Document");
}

 

How to Record Audio in Java?

       
import javax.sound.sampled.*;
import java.io.*;

public class JavaSoundRecorder {
 // record duration, in milliseconds
 static final long RECORD_TIME = 6000; // 1 minute

 // path of the wav file
 File wavFile = new File("RecordAudio.wav");

 // format of audio file
 AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

 // the line from which audio data is captured
 TargetDataLine line;

 /**
  * Defines an audio format
  */
 AudioFormat getAudioFormat() {
  float sampleRate = 8000.0F;//8000,11025,16000,22050,44100
  int sampleSizeInBits = 16;
  int channels =1;
  boolean signed = true;
  boolean bigEndian = true;
  AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,channels, signed, bigEndian);
  return format;
 }

 /**
  * Captures the sound and record into a WAV file
  */
 void start() {
  try {
   AudioFormat format = getAudioFormat();
   DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

   // checks if system supports the data line
   if (!AudioSystem.isLineSupported(info)) {
    System.out.println("Line not supported");
    System.exit(0);
   }
   line = (TargetDataLine) AudioSystem.getLine(info);
   line.open(format);
   line.start(); // start capturing

   System.out.println("Start capturing...");

   AudioInputStream ais = new AudioInputStream(line);

   System.out.println("Start recording...");

   // start recording
   AudioSystem.write(ais, fileType, wavFile);

  } catch (LineUnavailableException ex) {
   ex.printStackTrace();
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }

 /**
  * Closes the target data line to finish capturing and recording
  */
 void finish() {
  line.stop();
  line.close();
  System.out.println("Finished");
 }

 /**
  * Entry to run the program
  */
 public static void main(String[] args) {
  final JavaSoundRecorder recorder = new JavaSoundRecorder();

  // creates a new thread that waits for a specified
  // of time before stopping
  Thread stopper = new Thread(new Runnable() {
   public void run() {
    try {
     Thread.sleep(RECORD_TIME);
    } catch (InterruptedException ex) {
     ex.printStackTrace();
    }
    recorder.finish();
   }
  });

  stopper.start();

  // start recording
  recorder.start();
 }
}