Home Answers Viewqa Applet problem of writing to a local file ( JApplet )

 
 


shafi
problem of writing to a local file ( JApplet )
5 Answer(s)      4 years and 11 months ago
Posted in : Applet

View Answers

August 7, 2008 at 7:01 PM


Hi friend,

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;

//import controller.Controller;


public class GuestBook extends javax.swing.JApplet implements ActionListener {
private JLabel nameLabel;
private JLabel mailLabel;
private JLabel webLabel;
public JTextField webTextField;
public JTextField mailTextField;
public JTextField nameTextField;
private JPanel Panel1;
private JScrollPane commentScroll;
private JButton jButton1;
private JPanel buttonPanel;
private JButton submitButton;
private JPanel commentPanel;
public JTextArea commentTextArea;

/**
* Auto-generated main method to display this
* JApplet inside a new JFrame.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
GuestBook gbook = new GuestBook();
frame.getContentPane().add(gbook);
((JComponent)frame.getContentPane()).setPreferredSize(gbook.getSize());
frame.setSize(500,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
public GuestBook() {
super();
initGUI();
}
private void initGUI() {
try {
GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
getContentPane().setLayout(thisLayout);
this.setSize(427, 349); {
Panel1 = new JPanel();
GroupLayout jPanel1Layout = new GroupLayout((JComponent)Panel1);
Panel1.setLayout(jPanel1Layout);
Panel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));{
webLabel = new JLabel();
webLabel.setText("web address:");
}
{
mailLabel = new JLabel();
mailLabel.setText("Email Address:");
}
{
nameTextField = new JTextField();
}
{
mailTextField = new JTextField();
}
{
webTextField = new JTextField();
}
{
nameLabel = new JLabel();
nameLabel.setText("Your name:");
}

August 7, 2008 at 7:02 PM


jPanel1Layout.setVerticalGroup(jPanel1Layout.createSequentialGroup().addContainerGap(24, 24)
.addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(nameTextField, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
.addComponent(nameLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(mailTextField, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
.addComponent(mailLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(19)
.addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(webLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(webTextField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE))
.addContainerGap(19, 19));
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap().addGroup(jPanel1Layout.createParallelGroup()
.addComponent(webLabel, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
.addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE)
.addGap(10))
.addComponent(mailLabel, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup()
.addComponent(nameTextField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 224, GroupLayout.PREFERRED_SIZE)
.addComponent(mailTextField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 224, GroupLayout.PREFERRED_SIZE)
.addComponent(webTextField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 224, GroupLayout.PREFERRED_SIZE))
.addContainerGap(22, 22));
}
{
commentPanel = new JPanel();
GroupLayout jPanel2Layout = new GroupLayout((JComponent)commentPanel);
commentPanel.setLayout(jPanel2Layout);
commentPanel.setBorder(BorderFactory.createTitledBorder("Comment:"));{
commentScroll = new JScrollPane();
{
commentTextArea = new JTextArea();
commentScroll.setViewportView(commentTextArea);
}
}
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createSequentialGroup().addContainerGap()
.addComponent(commentScroll, 0, 346, Short.MAX_VALUE)
.addContainerGap());
jPanel2Layout.setVerticalGroup(jPanel2Layout.createSequentialGroup()
.addComponent(commentScroll, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE)
.addContainerGap());
}
{
buttonPanel = new JPanel();
GroupLayout jPanel3Layout = new GroupLayout((JComponent)buttonPanel);
buttonPanel.setLayout(jPanel3Layout);
{
jButton1 = new JButton();
jButton1.setText("Reset");
jButton1.addActionListener(this);
}
{
submitButton = new JButton();
submitButton.setText("Submit");
submitButton.addActionListener(this);
}

August 7, 2008 at 7:03 PM


jPanel3Layout.setHorizontalGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap(161, Short.MAX_VALUE)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(submitButton, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
.addGap(6));
jPanel3Layout.setVerticalGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 0, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE)
.addComponent(submitButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE))
.addContainerGap());
}
thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
.addContainerGap()
.addComponent(Panel1, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commentPanel, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonPanel, 0, 33, Short.MAX_VALUE)
.addContainerGap());
thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
.addContainerGap(23, 23)
.addGroup(thisLayout.createParallelGroup()
.addComponent(Panel1, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 382, GroupLayout.PREFERRED_SIZE)
.addComponent(commentPanel, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 382, GroupLayout.PREFERRED_SIZE)
.addComponent(buttonPanel, GroupLayout.Alignment.LEADING, 0, 382, Short.MAX_VALUE))
.addContainerGap(22, 22));

} catch (Exception e) {
e.printStackTrace();
}
}


@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Reset")){
//JOptionPane.showMessageDialog(null,"comment is mandatory!", "Error", JOptionPane.ERROR_MESSAGE);
emptyFields();

}
if(e.getActionCommand().equals("Submit")){
Controller control = new Controller();
try {
control.name_TextField_getText = nameTextField.getText();
control.mail_TextField_getText = mailTextField.getText();
control.web_TextField_getText = webTextField.getText();
control.comment_TextArea_getText = commentTextArea.getText();
control.error = false;
control.writeToXmlFile();
emptyFields();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

}
public void emptyFields(){
nameTextField.setText("");
mailTextField.setText("");
webTextField.setText("");
commentTextArea.setText("");
}

}

August 7, 2008 at 7:04 PM


public interface HtmlConverter {

}
--------------------------------
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import java.io.*;
import java.util.Date;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Controller {

static private GuestBook guest = new GuestBook();
static private HtmlConverter converter = null;
//xml tags
String fName = "name";
String mail = "mail";
String date = "date";
String web = "web";
String comment = "comment";
//error attribute
public boolean error = false;
//class variables
public String name_TextField_getText = "";
public String mail_TextField_getText = "";
public String web_TextField_getText = "";
public String comment_TextArea_getText = "";
//
// Constructors
//
public Controller () { };

//
// Methods
//
public void writeToXmlFile()throws Exception{
File file = new File("comments.xml");
boolean exist = file.exists();
if(!exist){
sampleComment();
}
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.parse("comments.xml");
Element rootElement = document.getDocumentElement();
Element child = (Element)rootElement.getFirstChild();
Element newNode = (Element)child.cloneNode(false);
rootElement.appendChild(newNode);

Element name = document.createElement(fName);
name.appendChild(document.createTextNode(name_TextField_getText));
System.out.println("name filed: "+name_TextField_getText);
if(name_TextField_getText.equals("")){
JOptionPane.showMessageDialog(null,"Please enter Name!", "Error", JOptionPane.ERROR_MESSAGE);
error = true;
//return;
}
newNode.appendChild(name);
// email
Element email = document.createElement(mail);
email.appendChild(document.createTextNode(mail_TextField_getText));
System.out.println("mail: "+mail_TextField_getText);
if(mail_TextField_getText.equals("")){
JOptionPane.showMessageDialog(null,"Please enetr E-mail Address!", "Error", JOptionPane.ERROR_MESSAGE);
error = true;
return;
}

August 7, 2008 at 7:05 PM


newNode.appendChild(email);
//date
//Date d = new Date();
//Object d1 = (Object)d.getYear();
String d2 = "2008";
System.out.println("Date: "+d2);
Element dat = document.createElement(date);
dat.appendChild(document.createTextNode(d2));
newNode.appendChild(dat);
//web
Element webPage = document.createElement(web);
webPage.appendChild(document.createTextNode(web_TextField_getText));
newNode.appendChild(webPage);
//comment
Element com = document.createElement(comment);
com.appendChild(document.createTextNode(comment_TextArea_getText));
if(comment_TextArea_getText.equals("")){
JOptionPane.showMessageDialog(null,"Please enter comment!", "Error", JOptionPane.ERROR_MESSAGE);
error = true;
return;
}
newNode.appendChild(com);
//writting to file
File file1 = new File("comments.xml");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file1);
transformer.transform(source, result);
}
public void sampleComment()throws Exception{
File file = new File("comments.xml");
String come = "<guestbook>"+
"<comment>"+"<name>shafi</name>"+"<mail>shafi.tokhi@gmail.com</mail>"+
"<date>2008</date>"+"<web>www.xtokhi.googlepages.com</web>"+
"<com>Java Guest Book</com>"+"</comment>"+
"</guestbook>";
org.w3c.dom.Document xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(come)));

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(xmldoc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
}

private GuestBook getGuest ( ) {
return guest;
}

private HtmlConverter getConverter ( ) {
return converter;
}

}
----------------------------------------------------

Thanks.









Related Pages:
problem of writing to a local file ( JApplet ) - Applet
problem of writing to a local file ( JApplet )  Dear All, I want to program a guestbook using java applets but now I have problem of writing to a file from JApplet. it is working without any problem if i run the program using
Loading JApplet into Servlet - Applet
Loading JApplet into Servlet  Hi, I am in need of loading... classs. As of now, we are using tag to load JApplet, which is working only... the problem. Thanks, Desu
Image writing over URLConnection
. The problem is that when writing by ImageIO on URL what will the name of the file... problems trying to write an image I have succeeded in writing to the local HD using...Image writing over URLConnection  Hello, I am trying to write
Problem while using a HashMap for writing text ina RTF file. - Framework
Problem while using a HashMap for writing text ina RTF file.  Hi, I am trying to generate a RTF file using iText.jar, wherein I am taking... matched to the string then only write to the RTF file. Problem is Document writes
Writing xml file - Java Beginners
Writing xml file  Thank you for the quick response The values which...;Hi friend, Code to solve the problem : import java.io.*; import java.sql.... XmlServlet().createXmlTree(doc); System.out.println("Xml File Created
java program for writing xml file - Java Beginners
java program for writing xml file  Good morning i want to write values from my database(one table)into one xml file. Like i have 3 coloumns in my... xml file and storet that in particlar location. Please help me out Thanks
File saving and Writing
File saving and Writing   Hello Rose india..... I have a doubt... a "file create option" it will be ".csv" file and i want to write the data from arraylist into .csv file and i want to save that file so it will ask for "save
Writing and Reading A File
Writing and Reading A File  Hello, I've been trying to learn writing and reading data from file for our assignment, but just stuck on how to proceed... (FirstName, LastName, Age). I also made an empty file I named "contactsFile.txt" where
create archive file on local disk in oracle 9i
create archive file on local disk in oracle 9i  how to create archive file on local disk and insert it in the oracle 9i database by java and MySQL. plz send to whole description all about this urgently. Thanks
Local Maven Depenency
Local Maven Depenency  Hi, What is local maven dependency? How to manage local maven dependency? Thanks   Hi, If some library is not available on the public maven repository you can add it to the local maven
writing and appending to a file
writing and appending to a file  My input file includes data from... and values and writes into an existing file for 'male'. How can I do the same..." + " :class :" + Name);// appends the string to the file
Access a variable local and globally
Access a variable local and globally  how can we access a variable local and globel??   hello, if you want to access your variable with in the view then declare it in the view.h file and if you want your variable
File Writing - Java Beginners
File Writing  Hi... I need a syntax or logic or program by which we can write into the desired shell of the Excel file from console window...  Hi friend, I am sending you a link. This is will help you. Please
pom.xml local jar
pom.xml local jar  Hi, I have placed one jar file in the WEB-INF/lib folder now I wan't to use this jar in the maven build and test phases. How to use this jar file? Thanks
Writing Calculator Stateless Session Bean
' bean. Writing JSP and Web/Ear component Our JSP file access the session bean...Writing Calculator Stateless Session Bean... to build ear file. We will deploy our application using WebLogic console
pom.xml local jar
pom.xml local jar  Hi, I have placed one jar file in the WEB-INF/lib... to use this jar file? Thanks   HI, You can add following dependency in pom.xml file: <dependency> <groupId>mylibrary</groupId>
FTP file copy problem? - Java Beginners
FTP file copy problem?  Hi, Can any one tell me how to set file...-net-1.4.1.jar to copy files from local system to server. Eg: local file name ?test.doc... need local file time like (Today, December 29, 2009, 5:09:33 PM). Below code I am
problem in writing coding. Please help me.
problem in writing coding. Please help me.  Hi sir, my name is Logeswaran. I have problem in writing JSP coding for my university assigments. Actually I'm doing a Voting System. I need to know how to write JSP coding
Terms to be avoided while writing for the Web
Terms to be avoided while writing for the Web  ... a file, instructions differ from browser to browser. So, whenever you provide... foreign, domestic, local should be avoided if your audience will be global
Change Local Repository
In this section, you will learn to change the default local repository of Maven using setting.xml configuration file
Browse Excel File Problem - Development process
displayed when i browse the file. What is the problem?  Hi Friend...") showxlsFileTable(filepath) var file = Components.classes["@mozilla.org/file/local;1...Browse Excel File Problem  I am using a web application,in which i
Writing Actions
Writing Actions The Action is responsible for controlling of data flow within an application. You can make any java class as action. But struts have some... the method name in Action mapping in struts.xml file. To get model reference
counting the values in input file and and writing the output to a file
counting the values in input file and and writing the output to a file  Can any one please correct this code. This is to read a file and later...-code/16483-counting-values-input-file-writing-output-file.html this code
Writing Log Records to a Log File
Writing Log Records to a Log File       This section demonstrates for writing log records to a log file. Logger provides different types of level like: warning, info
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks for quick response, I want to insert text at some particular line number.. after line number four my text will display in text file using java program
Writing a file using servlets - JSP-Servlet
Writing a file using servlets  I'm using a servlet to read an input... reading the data and creating a file in my space. but it is not writing..., but its not writing in the xyz.txt file. I think writing in a servlet should
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks..... after line number four my text will display in text file using java program  ... = ""; int lineNo; try { File f=new File("c
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks..... after line number four my text will display in text file using java program  ... = ""; int lineNo; try { File f=new File("c
Problem reading word file
Problem reading word file  Deepak you provide me code for extarcting equation from a word file and also to write in a word file.But when I again want to read preveously created word file(created by your code) it gives an error
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.  Hello, I would like to know how to write... stumped when it comes to reading the file and writing to a new file. My code
application context file problem
application context file problem  how to configure junit application context file with struts........? it is not finding sessionfactory method
Having a hard time writing program to calculate test scores..........
Having a hard time writing program to calculate test scores..........  i need a program that does this:Standardized Test Scores A local high... the scores are stored in a file (scores.txt) that you will need to download. Input
File Uploading Problem
File Uploading Problem  I have a file uploading code but it create problem $(document).ready(function(){ $('#upload').click(function(){ var... it gives the problem org.apache.commons.fileupload.FileUploadException
File Uploading Problem
File Uploading Problem  I have a file uploading code but it create problem $(document).ready(function(){ $('#upload').click(function(){ var... it gives the problem org.apache.commons.fileupload.FileUploadException
problem with main - Java Beginners
problem with main   import javax.swing.*; import java.awt.*; public class YellowFace extends JApplet { public static final int FACE... a problem. when i compile it appears this message: java.lang.NoSuchMethodError: main
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.  Hello, I would like to know how to write... it comes to reading the file and writing to a new file. My code is as follows
jboss with local entity bean - Development process
jboss with local entity bean  We are using eclipse version 3.4.0... were not getting bonded with the server if the entity bean is local, when we.... Is it a real problem with JBOSS 4.2 or are we going wrong somewhere? 2. Jboss
Portal Development Environment in local machine [Open Source]
Portal Development Environment in local machine [Open Source]  Hello... for Eclipse with Weblogic portal'. IDE is very heavy [350 MB zip file] and I need...? Download a file consist of Light weight Eclipse IDE [Eclipse is preferable as i am
struts jar file problem
struts jar file problem  hi.. I'm using struts-core-1.3.9.jar. it works well if am using ma application with internet but it shows me an error while initializing ActionServlet when i disconnected to Internet The error stack trace
File
File   How to find all files in our local computer using java
without writing web.xml file we can write servlet program
without writing web.xml file we can write servlet program  Sir Morning... Sir I have one Question "without writing web.xml file we can write servlet program". if yes which way? if no why? but without use Annotation........ Plz
Problem in getting file path in js
Problem in getting file path in js  hi, I am using ofbiz framework , How i can get the file path in javascript for input type = "file" and i am using only firefox not other browser. so please help me it is very important for me
Form Processing Problem
; // creating a new file with the same name and writing the content in new file...; //this loop converting the uploaded file into byte code...; } String file = new String(dataBytes); //for saving
problem while reading .csv file
problem while reading .csv file  I have a problem here..... i am reading a .csv extention file which has some value....but the problem is der is an amount column which contains , in between (eg) 3,899.00 which inturns creates
Reading and Writing files - Java Beginners
Reading and Writing files  Hello, please help me to Develop a simple... from a file. After welcoming the users, ask them for their name and save it to the file. Use the ClassLoader and Properties classes to load the file. You will need
Problem with appending data to the end of file
Problem with appending data to the end of file  MY JSP CODE... successfully</h1>"); %> </body> </html> JAVA CLASS FILE CODE... { public static void add(String name,String mail,String path) throws IOException { File
Java Write To File Append
the text when you are writing in a text file. Appending a text means that the text... the older text when you are writing again to an existing file. To achieve the solution of this problem at first I have created a text file named "
reading multiple files from a directory and writing them into a single file
reading multiple files from a directory and writing them into a single file... file i get an empty text file can you guide me how to do... static void main(String[]args) throws IOException{ File Folder = new
Spring Context - Writing Application Context
Spring Context - Writing Application Context  ... by defining the Application context definition file (applicationContext-hibernate.xml). This file is used by context loader servlet to initialize the Spring
accessing data from a json file writing javascript or using jQuery
accessing data from a json file writing javascript or using jQuery  I... this huge json file containing several objects that contain arrays for the objects... page is built from this json file, but I can't figure out how to code