Language Translator

Showing posts with label CODES. Show all posts
Showing posts with label CODES. Show all posts

SWING PROGRESS MONITOR (JPROGRESSMONITOR)

package progressmonitorexample;

import javax.swing.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.awt.Insets;
import java.awt.BorderLayout;
import java.util.*;
import java.util.concurrent.*;

public class ProgressMonitorExample extends JPanel implements ActionListener, PropertyChangeListener {
private static final int DEFAULT_WIDTH = 700;
private static final int DEFAULT_HEIGHT = 350;
private JButton copyButton;
private JTextArea console;
private ProgressMonitor progressMonitor;
private CopyFiles operation;

public static void main(String[] args) {
// tell the event dispatch thread to schedule the execution
// of this Runnable (which will create the example app GUI) for a later time
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// create example app window
JFrame frame = new JFrame("Progress Monitor Example");
// application will exit on close
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// create example app content pane
// ProgressMonitorExample constructor does additional GUI setup
JComponent contentPane = new ProgressMonitorExample();
contentPane.setOpaque(true);
frame.setContentPane(contentPane);

// display example app window
frame.setVisible(true);
}
});
}

public ProgressMonitorExample() {
// set up the copy files button
copyButton = new JButton("Copy Files");
copyButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(copyButton);

// set up the console for display of operation output
console = new JTextArea(15,60);
console.setMargin(new Insets(5,5,5,5));
console.setEditable(false);
add(new JScrollPane(console), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}

public void actionPerformed(ActionEvent event) {
// make sure there are files to copy
File srcDir = new File("in");
if (srcDir.exists() && (srcDir.listFiles() != null && srcDir.listFiles().length > 0)) {
// set up the destination directory
File destDir = new File("out");
// create the progress monitor
progressMonitor = new ProgressMonitor(ProgressMonitorExample.this,
"Operation in progress...",
"", 0, 100);
progressMonitor.setProgress(0);

// schedule the copy files operation for execution on a background thread
operation = new CopyFiles(srcDir, destDir);
// add ProgressMonitorExample as a listener on CopyFiles;
// of specific interest is the bound property progress
operation.addPropertyChangeListener(this);
operation.execute();
// we're running our operation; disable copy button
copyButton.setEnabled(false);
} else {
console.append("The sample application needs files to copy."
+ " Please add some files to the in directory"
+ " located at the project root.");
}
}

// executes in event dispatch thread
public void propertyChange(PropertyChangeEvent event) {
// if the operation is finished or has been canceled by
// the user, take appropriate action
if (progressMonitor.isCanceled()) {
operation.cancel(true);
} else if (event.getPropertyName().equals("progress")) {
// get the % complete from the progress event
// and set it on the progress monitor
int progress = ((Integer)event.getNewValue()).intValue();
progressMonitor.setProgress(progress);
}
}

class CopyFiles extends SwingWorker {
private static final int PROGRESS_CHECKPOINT = 10000;
private File srcDir;
private File destDir;

CopyFiles(File src, File dest) {
this.srcDir = src;
this.destDir = dest;
}

// perform time-consuming copy task in the worker thread
@Override
public Void doInBackground() {
int progress = 0;
// initialize bound property progress (inherited from SwingWorker)
setProgress(0);
// get the files to be copied from the source directory
File[] files = srcDir.listFiles();
// determine the scope of the task
long totalBytes = calcTotalBytes(files);
long bytesCopied = 0;

while (progress < 100 && !isCancelled()) {
// copy the files to the destination directory
for (File f : files) {
File destFile = new File(destDir, f.getName());
long previousLen = 0;

try {
InputStream in = new FileInputStream(f);
OutputStream out = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int counter = 0;
int len;

while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
counter += len;
bytesCopied += (destFile.length() - previousLen);
previousLen = destFile.length();
if (counter > PROGRESS_CHECKPOINT || bytesCopied == totalBytes) {
// get % complete for the task
progress = (int)((100 * bytesCopied) / totalBytes);
counter = 0;
CopyData current = new CopyData(progress, f.getName(),
getTotalKiloBytes(totalBytes),
getKiloBytesCopied(bytesCopied));

// set new value on bound property
// progress and fire property change event
setProgress(progress);

// publish current progress data for copy task
publish(current);
}
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return null;
}

// process copy task progress data in the event dispatch thread
@Override
public void process(List data) {
if(isCancelled()) { return; }
CopyData update = new CopyData(0, "", 0, 0);
for (CopyData d : data) {
// progress updates may be batched, so get the most recent
if (d.getKiloBytesCopied() > update.getKiloBytesCopied()) {
update = d;
}
}

// update the progress monitor's status note with the
// latest progress data from the copy operation, and
// additionally append the note to the console
String progressNote = update.getKiloBytesCopied() + " of "
+ update.getTotalKiloBytes() + " kb copied.";
String fileNameNote = "Now copying " + update.getFileName();

if (update.getProgress() < 100) {
progressMonitor.setNote(progressNote + " " + fileNameNote);
console.append(progressNote + "\n" + fileNameNote + "\n");
} else {
progressMonitor.setNote(progressNote);
console.append(progressNote + "\n");
}
}

// perform final updates in the event dispatch thread
@Override
public void done() {
try {
// call get() to tell us whether the operation completed or
// was canceled; we don't do anything with this result
Void result = get();
console.append("Copy operation completed.\n");
} catch (InterruptedException e) {

} catch (CancellationException e) {
// get() throws CancellationException if background task was canceled
console.append("Copy operation canceled.\n");
} catch (ExecutionException e) {
console.append("Exception occurred: " + e.getCause());
}
// reset the example app
copyButton.setEnabled(true);
progressMonitor.setProgress(0);
}

private long calcTotalBytes(File[] files) {
long tmpCount = 0;
for (File f : files) {
tmpCount += f.length();
}
return tmpCount;
}

private long getTotalKiloBytes(long totalBytes) {
return Math.round(totalBytes / 1024);
}

private long getKiloBytesCopied(long bytesCopied) {
return Math.round(bytesCopied / 1024);
}
}

class CopyData {
private int progress;
private String fileName;
private long totalKiloBytes;
private long kiloBytesCopied;

CopyData(int progress, String fileName, long totalKiloBytes, long kiloBytesCopied) {
this.progress = progress;
this.fileName = fileName;
this.totalKiloBytes = totalKiloBytes;
this.kiloBytesCopied = kiloBytesCopied;
}

int getProgress() {
return progress;
}

String getFileName() {
return fileName;
}

long getTotalKiloBytes() {
return totalKiloBytes;
}

long getKiloBytesCopied() {
return kiloBytesCopied;
}
}
}

READING XML THROUGH JAVASCRIPT

READING XML THROUGH JAVASCRIPT

XML.load = function(url) {
var xmldoc = XML.newDocument();
xmldoc.async = false;
xmldoc.load(url);
return xmldoc;
};
XML.newDocument = function(rootTagName, namespaceURL) {
if (!rootTagName) rootTagName = "";
if (!namespaceURL) namespaceURL = "";
if (document.implementation && document.implementation.createDocument) {
// This is the W3C standard way to do it
return document.implementation.createDocument(namespaceURL,
rootTagName, null);
}
else { // This is the IE way to do it
// Create an empty document as an ActiveX object
// If there is no root element, this is all we have to do
var doc = new ActiveXObject("MSXML2.DOMDocument");

// If there is a root tag, initialize the document
if (rootTagName) {
// Look for a namespace prefix
var prefix = "";
var tagname = rootTagName;
var p = rootTagName.indexOf(':');


if (p != -1) {
prefix = rootTagName.substring(0, p);
tagname = rootTagName.substring(p+1);
}

// If we have a namespace, we must have a namespace prefix
// If we don't have a namespace, we discard any prefix
if (namespaceURL) {
if (!prefix) prefix = "a0"; // What Firefox uses
}
else prefix = "";

// Create the root element (with optional namespace) as a
// string of text
var text = "<" + (prefix?(prefix+":"):"") + tagname +
(namespaceURL
?(" xmlns:" + prefix + '="' + namespaceURL +'"')
:"") +
"/>";
// And parse that text into the empty document
doc.loadXML(text);
}
return doc;
}
};



file: readxml.js
function readXmlFile() {
url = 'http://rorbuilder.info/pl/test123';

doc = XML.load(url);
alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
}

SWING JTREE EXAMPLE

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

public class JTreeDemo
{
public static void main(String [] arg)
{
JTreeDemo obj = new JTreeDemo();
}

public JTreeDemo()
{
JFrame frame = new JFrame("JTree Demo");
Container c = frame.getContentPane();
c.setLayout( new BorderLayout() );

//Create top node of a tree
final DefaultMutableTreeNode top = new DefaultMutableTreeNode("Course");

//Create a subtree UG
final DefaultMutableTreeNode UG = new DefaultMutableTreeNode("UG");
top.add(UG);
final DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("B.E");
UG.add(a1);
final DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("B.C.A");
UG.add(a2);
final DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("B.Sc");
UG.add(a3);
final DefaultMutableTreeNode a4 = new DefaultMutableTreeNode("B.Com");
UG.add(a4);
final DefaultMutableTreeNode a5 = new DefaultMutableTreeNode("B.A");
UG.add(a5);



//Create a subtree PG
final DefaultMutableTreeNode PG = new DefaultMutableTreeNode("PG");
top.add(PG);
final DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("M.E");
PG.add(b1);
final DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("M.C.A");
PG.add(b2);
final DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("M.Sc");
PG.add(b3);
final DefaultMutableTreeNode b4 = new DefaultMutableTreeNode("M.Com");
PG.add(b4);
final DefaultMutableTreeNode b5 = new DefaultMutableTreeNode("M.A");
PG.add(b5);

//Creating tree
final JTree tree = new JTree(top);

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
final JScrollPane jsp = new JScrollPane(tree,v,h);
c.add(jsp,BorderLayout.CENTER );

final JTextField text = new JTextField("",20);
c.add(text,BorderLayout.SOUTH);

tree.addMouseListener( new MouseAdapter()
{
public void mouseClicked( MouseEvent me)
{
TreePath tp = tree.getPathForLocation(me.getX(),me.getY() );
if( tp != null )
text.setText(tp.toString() );
else
text.setText("");
}
}
);

frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

SWING JSLIDER EXAMPLE

E

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

public class JSliderDemo
{
public static void main(String[] a)
{

JFrame frame = new JFrame("JSlider Demo");
Container c = frame.getContentPane();
c.setLayout( new FlowLayout() );

final JTextField text = new JTextField("A picture worth more than thousands words" );
text.setFont(new Font("Serif",Font.PLAIN,30));
text.setEditable(false);

final JSlider fontSizeSlider = new JSlider(SwingConstants.HORIZONTAL,0,45,30);
fontSizeSlider.setMajorTickSpacing(1);

fontSizeSlider.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int fontSize;
fontSize = fontSizeSlider.getValue();
text.setFont( new Font("Serif",Font.PLAIN,fontSize));
}
}
);


c.add(text);
c.add(fontSizeSlider);

frame.setSize(550,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

SWING TABBEDPANE EXAMPLE

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

public class JTabbedPaneDemo
{
public static void main(String[] arg)
{
JTabbedPaneDemo obj = new JTabbedPaneDemo();
}

public JTabbedPaneDemo()
{
JFrame frame = new JFrame("Tabbed pane demo");
Container c = frame.getContentPane();


JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Country", new CountryPanel() );
jtp.addTab("State", new StatePanel() );
jtp.addTab("City", new CityPanel() );

c.add(jtp);
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

class CountryPanel extends JPanel
{
public CountryPanel()
{
String item[] = { "India", "China", "UK", "USA", "Russia" };
JComboBox combo = new JComboBox(item);
add(combo);
}
}

class StatePanel extends JPanel
{
public StatePanel()
{
JButton b1 = new JButton("Tamil Nadu");
JButton b2 = new JButton("Maharastra");
JButton b3 = new JButton("Kerala");
add(b1);
add(b2);
add(b3);
}
}


class CityPanel extends JPanel
{
public CityPanel()
{
JCheckBox b1 = new JCheckBox("Chennai");
JCheckBox b2 = new JCheckBox("Delhi");
JCheckBox b3 = new JCheckBox("Mumbai");
add(b1);
add(b2);
add(b3);
}
}

Drag And Drop using javascript


<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>


"http://www.w3.org/TR/html4/loose.dtd">




JSP Page





Click -- > Drag and Drop any item



Item #1


Item #2


Item #3


Item #4












Java Mail Code To Send EMAIL

E-Mailing Through Java Mail

* You use the JavaMail API where as JavaMail implementation providers implement the JavaMail API to give you a JavaMail client (Java JAR file). Sun gives you mail.jar which has Sun's SMTP, POP3 and IMAP client implementations along with the JavaMail API. This is sufficient to send and receive e-mail but not to read or post to newgroups which use NNTP.

Sample Code to Send E-Mail

* To compile and run, you must have mail.jar (from the JavaMail download) and activation.jar (from the JavaBeans Activation Framework download) in Java classpath.

* You need to replace email addresses and mail server with your values where noted. Username and password is generally not needed to send e-mail although your ISP may still require it to prevent spam from going through its systems.

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

import javax.activation.*;

// Send a simple, single part, text/plain e-mail

public class TestEmail {

public static void main(String[] args) {

// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!

String to = "vipan@vipan.com";

String from = "vipan@vipan.com";

// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!

String host = "smtp.yourisp.net";

// Create properties, get Session

Properties props = new Properties();

// If using static Transport.send(),

// need to specify which host to send it to

props.put("mail.smtp.host", host);

// To see what is going on behind the scene

props.put("mail.debug", "true");

Session session = Session.getInstance(props);

try {

// Instantiatee a message

Message msg = new MimeMessage(session);

//Set message attributes

msg.setFrom(new InternetAddress(from));

InternetAddress[] address = {new InternetAddress(to)};

msg.setRecipients(Message.RecipientType.TO, address);

msg.setSubject("Test E-Mail through Java");

msg.setSentDate(new Date());

// Set message content

msg.setText("This is a test of sending a " +

"plain text e-mail through Java.\n" +

"Here is line 2.");

//Send the message

Transport.send(msg);

}

catch (MessagingException mex) {

// Prints all nested (chained) exceptions as well

mex.printStackTrace();

}

}

}//End of class

Sample Code to Send Multipart E-Mail, HTML E-Mail and File Attachments

* To compile and run, you must have mail.jar (from the JavaMail download) and activation.jar (from the JavaBeans Activation Framework download) in Java classpath.

* You need to replace email addresses and mail server with your values where noted.

* This sample code has debugging turned on ("mail.debug") to see what is going on behind the scenes in JavaMail code.

import java.util.*;

import java.io.*;

import javax.mail.*;

import javax.mail.internet.*;

import javax.activation.*;

public class SendMailUsage {

public static void main(String[] args) {

// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!

String to = "you@yourisp.net";

String from = "you@yourisp.net";

// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!

String host = "smtpserver.yourisp.net";

// Create properties for the Session

Properties props = new Properties();

// If using static Transport.send(),

// need to specify the mail server here

props.put("mail.smtp.host", host);

// To see what is going on behind the scene

props.put("mail.debug", "true");

// Get a session

Session session = Session.getInstance(props);

try {

// Get a Transport object to send e-mail

Transport bus = session.getTransport("smtp");

// Connect only once here

// Transport.send() disconnects after each send

// Usually, no username and password is required for SMTP

bus.connect();

//bus.connect("smtpserver.yourisp.net", "username", "password");

// Instantiate a message

Message msg = new MimeMessage(session);

// Set message attributes

msg.setFrom(new InternetAddress(from));

InternetAddress[] address = {new InternetAddress(to)};

msg.setRecipients(Message.RecipientType.TO, address);

// Parse a comma-separated list of email addresses. Be strict.

msg.setRecipients(Message.RecipientType.CC,

InternetAddress.parse(to, true));

// Parse comma/space-separated list. Cut some slack.

msg.setRecipients(Message.RecipientType.BCC,

InternetAddress.parse(to, false));

msg.setSubject("Test E-Mail through Java");

msg.setSentDate(new Date());

// Set message content and send

setTextContent(msg);

msg.saveChanges();

bus.sendMessage(msg, address);

setMultipartContent(msg);

msg.saveChanges();

bus.sendMessage(msg, address);

setFileAsAttachment(msg, "C:/WINDOWS/CLOUD.GIF");

msg.saveChanges();

bus.sendMessage(msg, address);

setHTMLContent(msg);

msg.saveChanges();

bus.sendMessage(msg, address);

bus.close();

}

catch (MessagingException mex) {

// Prints all nested (chained) exceptions as well

mex.printStackTrace();

// How to access nested exceptions

while (mex.getNextException() != null) {

// Get next exception in chain

Exception ex = mex.getNextException();

ex.printStackTrace();

if (!(ex instanceof MessagingException)) break;

else mex = (MessagingException)ex;

}

}

}

// A simple, single-part text/plain e-mail.

public static void setTextContent(Message msg) throws MessagingException {

// Set message content

String mytxt = "This is a test of sending a " +

"plain text e-mail through Java.\n" +

"Here is line 2.";

msg.setText(mytxt);

// Alternate form

msg.setContent(mytxt, "text/plain");

}

// A simple multipart/mixed e-mail. Both body parts are text/plain.

public static void setMultipartContent(Message msg) throws MessagingException {

// Create and fill first part

MimeBodyPart p1 = new MimeBodyPart();

p1.setText("This is part one of a test multipart e-mail.");

// Create and fill second part

MimeBodyPart p2 = new MimeBodyPart();

// Here is how to set a charset on textual content

p2.setText("This is the second part", "us-ascii");

// Create the Multipart. Add BodyParts to it.

Multipart mp = new MimeMultipart();

mp.addBodyPart(p1);

mp.addBodyPart(p2);

// Set Multipart as the message's content

msg.setContent(mp);

}

// Set a file as an attachment. Uses JAF FileDataSource.

public static void setFileAsAttachment(Message msg, String filename)

throws MessagingException {

// Create and fill first part

MimeBodyPart p1 = new MimeBodyPart();

p1.setText("This is part one of a test multipart e-mail." +

"The second part is file as an attachment");

// Create second part

MimeBodyPart p2 = new MimeBodyPart();

// Put a file in the second part

FileDataSource fds = new FileDataSource(filename);

p2.setDataHandler(new DataHandler(fds));

p2.setFileName(fds.getName());

// Create the Multipart. Add BodyParts to it.

Multipart mp = new MimeMultipart();

mp.addBodyPart(p1);

mp.addBodyPart(p2);

// Set Multipart as the message's content

msg.setContent(mp);

}

// Set a single part html content.

// Sending data of any type is similar.

public static void setHTMLContent(Message msg) throws MessagingException {

String html = "" +<o:p></o:p></p> <p style="font-family: georgia;" class="MsoPlainText">msg.getSubject() +<o:p></o:p></p> <p style="font-family: georgia;" class="MsoPlainText">"

" +

msg.getSubject() +

"

This is a test of sending an HTML e-mail" +

" through Java.";

// HTMLDataSource is an inner class

msg.setDataHandler(new DataHandler(new HTMLDataSource(html)));

}

/*

* Inner class to act as a JAF datasource to send HTML e-mail content

*/

static class HTMLDataSource implements DataSource {

private String html;

public HTMLDataSource(String htmlString) {

html = htmlString;

}

// Return html string in an InputStream.

// A new stream must be returned each time.

public InputStream getInputStream() throws IOException {

if (html == null) throw new IOException("Null HTML");

return new ByteArrayInputStream(html.getBytes());

}

public OutputStream getOutputStream() throws IOException {

throw new IOException("This DataHandler cannot write HTML");

}

public String getContentType() {

return "text/html";

}

public String getName() {

return "JAF text/html dataSource to send e-mail only";

}

}

} //End of class