URGETN HELP NEEDED! JAVA APPLET READING FILE

Hi everyone
I need to hand in this assignment today
Im trying to read from a file and read it onto the screen, my code keeps showing up an error
'missing method body, or declare abstract'
This is coming up for the
public statuc void main(String[] args);
and the
public void init();
Here is my code:
import java.io.*;
import java.awt.*;
import java.applet.*;
public class Empty_3 extends Applet {
TextArea ta = new TextArea();
public static void main(String[] args);
public void init();
setLayout(new BorderLayout());
add(ta, BorderLayout.CENTER);
try {
InputStream in =
getClass().getResourceAsStream("test1.txt");
InputStreamReader isr =
new InputStreamReader(in);
BufferedReader br =
new BufferedReader(isr);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
ta.setText(sw.toString());
} catch (IOException io) {
ta.setText("Ooops");
Can anyone help me please?
Is this the best way of doing this? Once i read the file i want to perform a frequency analysis on the words so if there is a better method for this then please let me know!
Thankyou
Matt

Whether it is urgent or not, does not interest us. It might be urgent for you but for nobody else.
Writing all-capitals is considered shouting and rude.
// Use code tags for source.

Similar Messages

  • Applet read file on web

    Can applet read file on web?
    I try to write an applet that read the file on web i.e. http://lcoalhost:8080/test.txt
    The HTML page contain the applet is placed on http://localhost:8080
    URI URItemp= new URI("file:///test.txt");
    File Filetemp = new File(URItemp);
    BufferReader in = new BufferReader(new InputStreamReader(new FileInputStream(Filetemp)));the above cannot work
    Error : access denied (java.io.FilePermission \test.txt read)
    And then I add
    FilePermission fp = new java.io.FilePermission("file:///test.txt", "read");still cannot work
    Cound anyone tell me that is possible to do what I want to do?
    If yes, how?
    Thanks!!

    Applets are downloaded from web servers and execute on the client machine.
    Therefore they have no access to the web server file system, signed or not.
    They could have access to the client file system (the machine where they run),
    but for security reasons only signed applets have this privilege.
    So to answer your question, you sign if you want to access client files.
    To access web server files, you don't need to sign the applet, but you need
    to provide some method of accessing files remotely, for instance:
    - Files published for the web can be read using HTTP
    - Files can be read or writen with the help of an FTP server on the same machine as the web server
    - A servlet running on the HTTP server can collaborate with your applet to exchange files

  • I am trying to use an education program that needs Java applets to install and use and it will not use Safari. When I download IE from the web it will not install. How can I get a browser that will work on my MacAir for travel use of this program?

    I am trying to use and education program that needs Java applets and it will not run on Safari. IE will not install from the web. How do I get a browser that will work to install so I can use this program when I travel.

    Try using FireFox. IE will only run on a Mac if you run Windows on the Mac.
    Windows on Intel Macs
    There are presently several alternatives for running Windows on Intel Macs.
    Install the Apple Boot Camp software.  Purchase Windows 7 or Windows 8.  Follow instructions in the Boot Camp documentation on installation of Boot Camp, creating Driver CD, and installing Windows.  Boot Camp enables you to boot the computer into OS X or Windows.
    Parallels Desktop for Mac and Windows XP, Vista Business, Vista Ultimate, or Windows 7.  Parallels is software virtualization that enables running Windows concurrently with OS X.
    VM Fusion and Windows XP, Vista Business, Vista Ultimate, or Windows 7.  VM Fusion is software virtualization that enables running Windows concurrently with OS X.
    CrossOver which enables running many Windows applications without having to install Windows.  The Windows applications can run concurrently with OS X.
    VirtualBox is a new Open Source freeware virtual machine such as VM Fusion and Parallels that was developed by Solaris.  It is not as fully developed for the Mac as Parallels and VM Fusion.
    Note that Parallels and VM Fusion can also run other operating systems such as Linux, Unix, OS/2, Solaris, etc.  There are performance differences between dual-boot systems and virtualization.  The latter tend to be a little slower (not much) and do not provide the video performance of the dual-boot system. See MacTech.com's Virtualization Benchmarking for comparisons of Boot Camp, Parallels, and VM Fusion. A more recent comparison of Parallels, VM Fusion, and Virtual Box is found at Virtualization Benchmarks- Parallels 10 vs. Fusion 7 vs. VirtualBox. Boot Camp is only available with Leopard and later. Except for Crossover and a couple of similar alternatives like DarWine you must have a valid installer disc for Windows.
    You must also have an internal optical drive for installing Windows. Windows cannot be installed from an external optical drive.

  • Need help with Java applet, might need NetBeans URL

    I posted the below question. It was never answered, only I was told to post to the NetBeans help forum. Yet I don't see any such forum on this site. Can someone tell me where the NetBeans help forum is located (URL).
    Here is my original question:
    I have some Java source code from a book that I want to compile. The name of the file is HashTest.java. In order to compile and run this Java program I created a project in the NetBeans IDE named javaapplication16, and I created a class named HashTest. Once the project was created, I cut and pasted the below source code into my java file that was default created for HashTest.java.
    Now I can compile and build the project with no errors, but when I try and run it, I get a dialog box that says the following below (Ignore the [...])
    [..................Dialog Box......................................]
    Hash Test class wasn't found in JavaApplication16 project
    Select the main class:
    <No main classes found>
    [..................Dialog Box......................................]
    Does anyone know what the problem is here? Why won't the project run?
    // Here is the source code: *****************************************************************************************************
    import java.applet.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import java.util.*;
    public class HashTest extends Applet implements ItemListener
    // public static void main(String[] args) {
    // Hashtable to add tile images
    private Hashtable imageTable;
    // a Choice of the various tile images
    private Choice selections;
    // assume tiles will have the same width and height; this represents
    // both a tile's width and height
    private int imageSize;
    // filename description of our images
    private final String[] filenames = { "cement.gif", "dirt.gif", "grass.gif",
    "pebbles.gif", "stone.gif", "water.gif" };
    // initializes the Applet
    public void init()
    int n = filenames.length;
    // create a new Hashtable with n members
    imageTable = new Hashtable(n);
    // create the Choice
    selections = new Choice();
    // create a Panel to add our choice at the bottom of the window
    Panel p = new Panel();
    p.add(selections, BorderLayout.SOUTH);
    p.setBackground(Color.RED);
    // add the Choice to the applet and register the ItemListener
    setLayout(new BorderLayout());
    add(p, BorderLayout.SOUTH);
    selections.addItemListener(this);
    // allocate memory for the images and load 'em in
    for(int i = 0; i < n; i++)
    Image img = getImage(getCodeBase(), filenames);
    while(img.getWidth(this) < 0);
    // add the image to the Hashtable and the Choice
    imageTable.put(filenames[i], img);
    selections.add(filenames[i]);
    // set the imageSize field
    if(i == 0)
    imageSize = img.getWidth(this);
    } // init
    // tiles the currently selected tile image within the Applet
    public void paint(Graphics g)
    // cast the sent Graphics context to get a usable Graphics2D object
    Graphics2D g2d = (Graphics2D)g;
    // save the Applet's width and height
    int width = getSize().width;
    int height = getSize().height;
    // create an AffineTransform to place tile images
    AffineTransform at = new AffineTransform();
    // get the currently selected tile image
    Image currImage = (Image)imageTable.get(selections.getSelectedItem());
    // tile the image throughout the Applet
    int y = 0;
    while(y < height)
    int x = 0;
    while(x < width)
    at.setToTranslation(x, y);
    // draw the image
    g2d.drawImage(currImage, at, this);
    x += imageSize;
    y += imageSize;
    } // paint
    // called when the tile image Choice is changed
    public void itemStateChanged(ItemEvent e)
    // our drop box has changed-- redraw the scene
    repaint();
    } // HashTest

    BigDaddyLoveHandles wrote:
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    That wasn't attention-grabbing enough apparantly. Let's try it again.
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}

  • Newbie need help wtih Java Applet noinit error

    Hi, i am having problem with a making this java applet application run, i am new to java but i am sure that my coding is right, because this what i typed from my java class book. Don't know why when i try to run it is say at the bottom of the windows explorer, "applet class name "noinit"". The code is listed below maybe someone could help me figure this out. I used NetBean to compile it, also I have the latest version of java but could not find a applet that come with the newest version of java so I'm using the j2sdk1.4.2_11 applet, and have added it to my system environment path. Maybe that could be the problem if so where do i get the newest version of the applet, because without doing what i did i could run applets in the first place. My other sample applet sample (demo's) that come with Java runs fine without any problem. Only when i run mine i get the message, "applet class name noinit".
    HTML file:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Welcome Applet</title>
    </head>
    <!-- Used to load the Java .class file -->
    <applet code="WelcomeApplet.class" width="300" height="45">
    alt="Your browser understands the <;APPLET> tag but isn't running the applet, for some reason."
         Your browser is completely ignoring the <APPLET> tag!
    </applet>
    <body>
    </body>
    </html>Java code:
    /* Fig. 3.6: WelcomeApplet.java
    *  My first applet in Java
    * Created on May 2, 2006, 2:50 AM
    // Java packages
    package appletjavafig3_6;
    import java.awt.Graphics;   // import class Graphics
    import javax.swing.JApplet; // import class JApplet
    public class WelcomeApplet extends JApplet {
        public WelcomeApplet(){
        // 3rd method that is called by default
        // draw text on applets's background
        public void paint( Graphics g)
            // call superclass version of method paint
            super.paint(g);
            // draw a String at x-coordinate 25 and y coordinate 25
            g.drawString("Welcome to Java Programming!", 25,25);
        } // end method paint
    } // WelcomeApplet

    Hi,
    Your applet code in the html should be
    <applet code="appletjavafig3_6.WelcomeApplet" width="300" height="45">
    alt="Your browser understands the <;APPLET> tag but isn't running the applet, for some reason."
         Your browser is completely ignoring the <APPLET> tag!
    </applet>As the class is inside a package named appletjavafig3_6, put the class file inside a folder named appletjavafig3_6. Put the html file outside this folder and test it.

  • (Urgent help needed) how to read txt file and store the data into 2D-array?

    Hi, I have a GUI which allow to choose file from the file chooser, and when "Read file" button is pressed, I want to show the array data into the textarea.
    The sample data is like this followed:
    -0.0007     -0.0061     0.0006
    -0.0002     0.0203     0.0066
    0     0.2317     0.008
    0.0017     0.5957     0.0008
    0.0024     1.071     0.0029
    0.0439     1.4873     -0.0003
    I want my program to scan through and store these data into 2D array.
    However for some reason, my source code issues errors, and I don't know what's wrong with it, seems to have a problem in StringTokenizer though. Can anybody help me?
    Thanks in advance.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.StringTokenizer;
    public class FileReduction1 extends JFrame implements ActionListener{
    // GUI features
    private BufferedReader fileInput;
    private JTextArea textArea;
    private JButton openButton, readButton,processButton,saveButton;
    private JTextField textfield;
    private JPanel pnlfile;
    private JPanel buttonpnl;
    private JPanel buttonbar;
    // Other fields
    private File fileName;
    private String[][] data;
    private int numLines;
    public FileReduction1(String s) {
    super(s);
    // Content pane
         Container cp = getContentPane();
         cp.setLayout(new BorderLayout());     
    // Open button Panel
    pnlfile=new JPanel(new BorderLayout());
         textfield=new JTextField();
         openButton = new JButton("Open File");
    openButton.addActionListener(this);
    pnlfile.add(openButton,BorderLayout.WEST);
         pnlfile.add(textfield,BorderLayout.CENTER);
         readButton = new JButton("Read File");
    readButton.addActionListener(this);
         readButton.setEnabled(false);
    pnlfile.add(readButton,BorderLayout.EAST);
         cp.add(pnlfile, BorderLayout.NORTH);
         // Text area     
         textArea = new JTextArea(10, 100);
    cp.add(new JScrollPane(textArea),BorderLayout.CENTER);
    processButton = new JButton("Process");
    //processButton.addActionListener(this);
    saveButton=new JButton("Save into");
    //saveButton.addActionListener(this);
    buttonbar=new JPanel(new FlowLayout(FlowLayout.RIGHT));
    buttonpnl=new JPanel(new GridLayout(1,0));
    buttonpnl.add(processButton);
    buttonpnl.add(saveButton);
    buttonbar.add(buttonpnl);
    cp.add(buttonbar,BorderLayout.SOUTH);
    /* ACTION PERFORMED */
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Open File")) getFileName();
         if (event.getActionCommand().equals("Read File")) readFile();
    /* OPEN THE FILE */
    private void getFileName() {
    // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
    if (result == JFileChooser.APPROVE_OPTION)
         fileName = fileChooser.getSelectedFile();
    textfield.setText(fileName.getName());
         if (checkFileName()) {
         openButton.setEnabled(false);
         readButton.setEnabled(true);
         // Obtain selected file
    /* READ FILE */
    private void readFile() {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines();
         data = new String[numLines][];
         // Read file
         readTheFile();
         // Output to text area     
         textArea.setText(data[0][0] + "\n");
         for(int index=0;index < data.length;index++)
    for(int j=1;j<data[index].length;j++)
    textArea.append(data[index][j] + "\n");
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines() {
    int counter = 0;
         // Open the file
         openFile();
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile();
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* READ FILE */
    private void readTheFile() {
    // Open the file
    int row=0;
    int col=0;
         openFile();
    System.out.println("Read the file");     
         // Loop through file incrementing counter
         try {
    String line = fileInput.readLine();
         while (line != null)
    StringTokenizer st=new StringTokenizer(line);
    while(st.hasMoreTokens())
    data[row][col]=st.nextToken();
    System.out.println(data[row][col]);
    col++;
    row++;
    closeFile();
    catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName() {
         if (fileName.exists()) {
         if (fileName.canRead()) {
              if (fileName.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* FILE HANDLING UTILITIES */
    /* OPEN FILE */
    private void openFile() {
         try {
         // Open file
         FileReader file = new FileReader(fileName);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File opened");
    /* CLOSE FILE */
    private void closeFile() {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    /* MAIN METHOD */
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException {
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Java.lang.NullpointException
    at FileReductoin1.readTheFile <FileReduction1.java :172>
    at FileReductoin1.readFile <FileReduction1.java :110>
    at FileReductoin1.actionPerformed <FileReduction1.java :71>
    .

    1) Next time use the CODE tags. this is way too much unreadable crap.
    2) The problem is your String[][] data.... the only place I see you do anything approching initializing it is
    data = new String[numLines][];I think you want to do this..
    data = new String[numLines][3];anyway that's why it's blowing up on the line
    data[row][col]=st.nextToken();

  • Need help with java applet

    Hi all,
    Am having trouble with a java applet that won't run under Mozilla, Seamonkey, and IE 6 but will run under IE 7 Beta 2. Am posting the error info below in the hope that someone can see what could be wrong as i don't want to upgrade user's to IE 7 since it's a beta and also since most of them use mozilla. thanks in advance:
    load: class com.crystaldecisions.ReportViewer.ReportViewer not found.
    java.lang.ClassNotFoundException: com.crystaldecisions.ReportViewer.ReportViewer
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed.
         at sun.applet.AppletClassLoader.getBytes(Unknown Source)
         at sun.applet.AppletClassLoader.access$100(Unknown Source)
         at sun.applet.AppletClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 10 more
    Exception in thread "Thread-5" java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletException(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletStatus(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Exception in thread "thread applet-com.crystaldecisions.ReportViewer.ReportViewer" java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletException(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)

    BigDaddyLoveHandles wrote:
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    That wasn't attention-grabbing enough apparantly. Let's try it again.
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}

  • Help!!! Need Java Applet to work in IE

    I found some applets (text scrollers) from the sun site that i wanted to use. downloaded them, but they do not work in IE that does not have JVM. in IE that does have JVM it says 'Java 1.1 Required' where the applet should be. is there a simple way to get sun java applets to work with IE and the MS Virtual Machine? I can't require my site visitors to have to download extra toys/plugins...

    If you are looking for a purely AWT scrolling applet. Here is one I wrote several years ago. Please note that there are some deprecated methods in it (mainly the thread start and stop methods). It will still compile though. If you want it, take it.
    Source:import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.net.*;
    public class ScrollApplet extends Applet implements Runnable
       /*=*********************
       * private data members *
       private Thread myThread = null;
       private boolean hasTextDisplayed;
       private int appletWidth, appletHeight;
       private int yPosition;
       private int xPosition;
       private Image textImage;
       private int imageWidth;
       private Graphics textGraphics;
       private Cursor oldCursor;
       private Cursor newCursor = new Cursor(Cursor.HAND_CURSOR);
       //parameters
       private int delay;
       private String displayText;
       private Color bgColor, fgColor;
       private int fontSize, fontStyle;
       private Font fontType;
       private String urlValue;
       /*=***************
       * applet methods *
       public void init()
          //assign values to private data members
          hasTextDisplayed = false;
          appletHeight = yPosition = getSize().height;
          appletWidth = xPosition = getSize().width;
          //set up the environment
          extractParameters();
          //determine the yPosition to place the image
          calculateYPosition();
          //set up the text image
          FontMetrics fm = getFontMetrics(fontType);
          imageWidth = fm.stringWidth(displayText);
          textImage = createImage(imageWidth, appletHeight);
          textGraphics = textImage.getGraphics();
          textGraphics.setColor(bgColor);
          textGraphics.fillRect(0,0,imageWidth,appletHeight);
          textGraphics.setColor(fgColor);
          textGraphics.setFont(fontType);
          textGraphics.drawString(displayText, 0, yPosition);
          oldCursor = this.getCursor();
          addMouseListener(new MouseAdapter() {
             public void mouseExited(MouseEvent e)
                if (urlValue != null) {
                   Component thisApplet = e.getComponent();
                   thisApplet.setCursor(oldCursor);
                showStatus(" ");
                myThread.resume();
             public void mouseEntered(MouseEvent e)
                myThread.suspend();
                if (urlValue != null) {
                   Component thisApplet = e.getComponent();
                   thisApplet.setCursor(newCursor);
                   showStatus(urlValue);
                else
                   showStatus("paused");
             public void mouseClicked(MouseEvent e)
                if (urlValue != null)
                   try {
                      URL u = new URL(urlValue);
                      getAppletContext().showDocument(u, "_self");
                   } catch(MalformedURLException ex) {
                   showStatus("MalformedURLException: " +ex);
       }//end init method
       public void start()
          myThread = new Thread(this);
          myThread.start();
       }//end start method
       public void update(Graphics g)
       //overwrote this method to avoid repainting of background before all text displays
          if (hasTextDisplayed == true)
             //repaint the background
             g.setColor(bgColor);
             g.fillRect(xPosition+imageWidth, 0, appletWidth - (xPosition + imageWidth),
                          appletHeight);
             g.setColor(fgColor);
          paint(g);
       }//end update method
       public void paint(Graphics g)
          setBackground(bgColor);
          g.drawImage(textImage,xPosition,0,this);
       }//end paint method
       public void stop()
       { myThread = null; }
       /*=*******************************************************************************
       * applet method getParameterInfo():                                              *
       * Returns information about the parameters that are understood by this applet.   *
       * An applet should override this method to return an array of Strings describing *
       * these parameters.  Each element of the array should be a set of three Strings  *
       * containing the name, the type, and a description.                              *
       public String[][] getParameterInfo()
          String parameterInfo[][] = {
             {"DELAYPARAM", "int", "The interval to pause in milliseconds"},
             {"TEXTPARAM", "string", "The text that will be displayed"},
             {"BGPARAM", "Color", "The bg color for the applet, in html format #FFFFFF"},
             {"FGPARAM", "Color", "The fg color for the text, in html format #FFFFFF"},
             {"FONTSIZEPARAM", "int", "The font size of the text"},
             {"FONTTYPEPARAM", "string", "The name of the font to use"},
             {"FONTSTYLEPARAM", "string", "bold, italic, or bold+italic"},
             {"URLPARAM", "string", "hyperlink"}
          return parameterInfo;
       }//end getParameterInfo method
       /*=*****************************************************************************
       * applet method getAppletInfo():                                               *
       * Returns information about this applet. An applet should override this method *
       * to return a String containing information about the author, version, and     *
       * copyright of the applet.                                                     *
       public String getAppletInfo()
          String infoAboutMe;
          infoAboutMe = new String(
             "Author:  Your Name Here/n" +
             "Description:  My first text scroller\n" +
             "Version: 1.0"
          return infoAboutMe;
       }//end getAppletInfo method
       /*=***************
       * thread methods *
       public void run()
          Thread current = Thread.currentThread();
          //loop until thread is stopped
          while (myThread == current)
             repaint();
             try {
                current.sleep(delay);
                xPosition--;
             } catch (InterruptedException e) {}
             if (xPosition <= (appletWidth - imageWidth))
                hasTextDisplayed = true;
             else
                hasTextDisplayed = false;
             if (xPosition == (0 - imageWidth))
                xPosition = appletWidth;
       }//end required run method
       /*=**********************************************************************
       * extractParameters():  Sets all parameter values, if any were provided *
       public void extractParameters()
          String delayValue = getParameter("DELAYPARAM");
          String textValue = getParameter("TEXTPARAM");
          String bgColorValue = getParameter("BGPARAM");
          String fgColorValue = getParameter("FGPARAM");
          String fontSizeValue = getParameter("FONTSIZEPARAM");
          String fontTypeValue = getParameter("FONTTYPEPARAM");
          String fontStyleValue = getParameter("FONTSTYLEPARAM");
          String urlParam = getParameter("URLPARAM");
          //set delay to one tenth of a second if missing parameter
          delay = ((delayValue == null) ? 100 : Integer.parseInt(delayValue));
          urlValue = (urlParam == null ? null : urlParam);
          displayText = ((textValue == null) ?
                new String("NO TEXT WAS PROVIDED!") :
                textValue);
          bgColor = determineColor(bgColorValue);
          fgColor = determineColor(fgColorValue);
          fontStyle = determineFontStyle(fontStyleValue);
          fontSize = ((fontSizeValue == null) ? 12 : Integer.parseInt(fontSizeValue));
          fontType = new Font(fontTypeValue, fontStyle, fontSize);
       }//end extractParameters method
       /*=*************************************************
       * determineColor():  returns the appropriate color *
       public Color determineColor(String value)
          return parseHTMLHex(value);
       }//end determineColor method
       /*=*****************************************************************************
       * parseHTMLHex(): parses an HTML hex (eg #FFFFFF) and returns the Color object *
       public static Color parseHTMLHex(String htmlHex) {
          Color color = new Color(220,220,220);  //default grey
          if (htmlHex != null) {
             String red = htmlHex.substring(1,3);
             String green = htmlHex.substring(3,5);
             String blue = htmlHex.substring(5);
             color = new Color(Integer.parseInt(red,16),
                           Integer.parseInt(green,16),
                           Integer.parseInt(blue,16));
          }//end if
          return color;
       }//end parseHTMLHex method
       /*=******************************************
       * determineFontStyle():  returns font sytle *
       public int determineFontStyle(String value)
          int returnVal;
          if (value == null)
             returnVal = Font.PLAIN;
          else if (value.equalsIgnoreCase("plain"))
             returnVal = Font.PLAIN;
          else if (value.equalsIgnoreCase("bold"))
             returnVal = Font.BOLD;
          else if (value.equalsIgnoreCase("italic"))
             returnVal = Font.ITALIC;
          else if (value.equalsIgnoreCase("bold+italic"))
             returnVal = Font.BOLD + Font.ITALIC;
          else
             returnVal = Font.PLAIN;
          return returnVal;
       }//end determineFontStyle method
       /*=**********************************************************
       * calculateYPosition(): want text to be in middle of applet *
       public void calculateYPosition()
          //wasYPositionCalculated = true;
          //make calculations to center font in applet window
          int appletMidHeight = appletHeight / 2;         //the middle of the applet
          FontMetrics fm = getFontMetrics(fontType);    //font metrics for current font
          int fontMidHeight = fm.getAscent() / 2;         //the middle of the font
          int currentFontSizeValue;                       //temp value for font size
          //if the font size if too big, fix it
          if ((currentFontSizeValue = fm.getAscent()) > appletHeight)
             //cycle through font sizes until find one that fits
             while (currentFontSizeValue > appletHeight)
                fontType = new Font(getParameter("FONTTYPEPARAM"), fontStyle, --fontSize);
                fm = getFontMetrics(fontType);
                currentFontSizeValue = fm.getAscent();
             //set the new values for the new font
             setFont(fontType);
             fm = getFontMetrics(fontType);
             fontMidHeight = fm.getAscent() / 2;
          yPosition = appletMidHeight + fontMidHeight - 3;
       }//end calculateYPosition()
    }//end applethtml:<HTML>
    <HEAD>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
    <TITLE>Test scroller applet</title>
    </head>
    <BODY>
    <h1>Scroller Applet</h1>
    <!--CODEBASE = "."-->
    <APPLET
      CODE     = "ScrollApplet.class"
      NAME     = "TestApplet"
      WIDTH    = 400
      HEIGHT   = 30
      HSPACE   = 0
      VSPACE   = 0
      ALIGN    = middle
    >
    <PARAM NAME="DELAYPARAM" VALUE="10">
    <PARAM NAME="TEXTPARAM" VALUE="Simple Old Scrolling Applet?">
    <PARAM NAME="BGPARAM" VALUE="#000000">
    <PARAM NAME="FGPARAM" VALUE="#CCCCCC">
    <PARAM NAME="FONTSIZEPARAM" VALUE="24">
    <PARAM NAME="FONTTYPEPARAM" VALUE="TimesRoman">
    <PARAM NAME="FONTSTYLEPARAM" VALUE="italic">
    <PARAM NAME="URLPARAM" VALUE="http://quote.yahoo.com/quotes?SYMBOLS=DISH">
    </applet>
    </body>
    </html>tajenkins

  • Applet + Read File??????

    Hello security gurus:
    Could somebody suggest an easy way to read a single xml file from originating on the same sever and directory where the applet resides? People say that an applet can access file from the working directory and all sub-directories this works fine on my system when
    executed directly from the appletviewer or the browser but when I load my program and it's dependencies in a webserver such as tomcat or apache it chokes on applet security exceptions. If someone could help I could stop
    beating my head on the desk where my workstation resides.
    Thanks, Ian

    Hi Bakrudeen,
    I�m a newbie into Java Applets ( so, Java too ), I work with C and C++, but now I need to do somethings using Java. One it�s that I need to do a Applet that read a xml file that�s into my webserver, in the same direcotry that my .class files are. First, I did a java class that run stand alone, it read the file perfectly, after I did a class that extends the applet class, but it didn�t found. Reading your e-mail, I had some questions, than, can you explain better your ideas ? Because, I have the plugins in my machine ( not in the server, the server doesn�t have anything about java, only the Apache server, my webpages and applet classes ), but I can�t read the file ? Another question is: how can I do to see the exceptions messagens to try looking for my errors ?
    See below the source code that I�m trying to use:
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class WS10Parser extends Applet {
    public int finished;     // 0 - n�o encerrado
    // 1 - encerrado
    // 2 - erro
    private JanelTexto janela;
    public void init() {
    janela = new JanelTexto();
    public void paint(Graphics g) {
    //          g.drawString("Welcome to Java!!", 50, 60 );
    * Fun��o para leitura do arquivo XML
    * Parametros:
    * - Nome do arquivo XML a ser lido
    * - Nome do Dispositivo a ser lido
    * - Modo de leitura do arquivo
    *     - 1 L� somente dados referentes ao dispositivo identificado pelo Nome
    *     - 0     L� informa��es de todos os Devices no arquivo
    //     public void ReadFile(String FileName, String DeviceName, int Mode) {
    public void ReadFile(String FileName) {
    finished = 0;
    URL url;
    try {
    url = new URL(getCodeBase(), FileName);
    janela.AddText("File name: " + url.toString());
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(url.openStream());
    // normalize text representation
    doc.getDocumentElement().normalize();
    janela.AddText("Root element of the doc is " + doc.getDocumentElement().getNodeName());
    NodeList listOfDevices = doc.getElementsByTagName("device");
    int totalDevices = listOfDevices.getLength();
    janela.AddText("Total no of devices : " + totalDevices);
    for(int s=0; s<listOfDevices.getLength() ; s++){
    Node firstDeviceNode = listOfDevices.item(s);
    if(firstDeviceNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstDeviceElement = (Element)firstDeviceNode;
    NodeList firstNameList = firstDeviceElement.getElementsByTagName("name");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    janela.AddText("Device Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
    NodeList lastNameList = firstDeviceElement.getElementsByTagName("timestamp");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    janela.AddText("TimeStamp : " + ((Node)textLNList.item(0)).getNodeValue().trim());
    NodeList listOfChannels = firstDeviceElement.getElementsByTagName("channel");
    int totalChannels = listOfChannels.getLength();
    janela.AddText("Total no of channels: " + totalChannels);
    for(int cont = 0; cont < listOfChannels.getLength(); cont++) {
    Node channelNode = listOfChannels.item(cont);
    if(channelNode.getNodeType() == Node.ELEMENT_NODE) {
    Element channelElement = (Element)channelNode;
    NodeList tagList = channelElement.getElementsByTagName("tag");
    Element tagElement = (Element)tagList.item(0);
    NodeList textTagList = tagElement.getChildNodes();
    janela.AddText("Tag: " + ((Node)textTagList.item(0)).getNodeValue().trim());
    NodeList valueList = channelElement.getElementsByTagName("value");
    Element valueElement = (Element)valueList.item(0);
    NodeList textValueList = valueElement.getChildNodes();
    janela.AddText("Value: " + ((Node)textValueList.item(0)).getNodeValue().trim());
    }//end of if clause
    }//end of for loop with s var
    finished = 1;
    }catch (SAXParseException err) {
    janela.AddText("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
    janela.AddText(" " + err.getMessage());
    finished = 2;
    }catch (SAXException e) {
    Exception x = e.getException();
    ((x == null) ? e : x).printStackTrace();
    finished = 3;
    }catch (Throwable t) {
    t.printStackTrace();
    finished = 4;
    private class JanelTexto extends JFrame {
    private JTextArea ta;
    public JanelTexto() {
    super("Teste Applet Novus");
    Box b = Box.createHorizontalBox();
    ta = new JTextArea(20, 30);
    b.add(new JScrollPane(ta));
    Container c = getContentPane();
    c.add(b);
    setSize(425, 200);
    show();
    public void AddText(String Text) {
    ta.append(Text + '\n');
    Thanks

  • Question about Java Applet Jar file signing.

    These questions pertain to Java 6 Standard Edition 1.6.0_22-b04 and later.
    I have gone through the Oracle Java Tutorial for generate public and private key information
    to sign a jar file, and how to sign the jar itself, all at
    [http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html]
    , and seek some clarification on the following related questions:
    -In order to "escape" the java applet sandbox that exists around the client's
    copy of the applet running in their web browser, ie.
    (something forbidden by default), is verification of the signed applet enough, or is a policy file required
    to stipulate these details?
    -using the policytool policy file generator, what do I need to add under "Principals"
    (if anything) when dealing with a Java applet? Are Codebase and SignedBy simply author information?
    -If I choose to use a java.security.Permission subclass object set up in equivalent fashion within the Applet,
    which class within the Applet jar do I instantiate that object in? Does it need to be mentioned
    in the applet's jar Manifest.MF file?
    -Is the "keystore database" a java language service/process which runs in
    the Server's memory and is simply accessed and started by default
    by the client verifier program (appletview/web browser)?
    -The public key certificate file (*.cer) is put in the webserver directory holding
    the Applet jar file (ie. Apache Tomcat, for example).
    -Presumably, the web browser detects the signed jar
    and certificate file, and provides the browser pop up menu asking the user
    about a new, non recognised certificate (initially).
    Is this so?
    -With this being the case, can the applet now escape
    the sandbox, be it with or without the stipulated
    policy permissions?

    848439 wrote:
    -In order to "escape" the java applet sandbox that exists around the client's
    copy of the applet running in their web browser, ie.
    (something forbidden by default), is verification of the signed applet enough, or is a policy file required
    to stipulate these details?Just sign the applet, the policy file is not necessary.
    -Is the "keystore database" a java language service/process which runs in
    the Server's memory and is simply accessed and started by default
    by the client verifier program (appletview/web browser)?No.
    -The public key certificate file (*.cer) is put in the webserver directory holding
    the Applet jar file (ie. Apache Tomcat, for example).No. For a signed Jar, all the information is contained inside the Jar.
    -Presumably, the web browser detects the signed jar
    and certificate file, and provides the browser pop up menu asking the user
    about a new, non recognised certificate (initially).
    Is this so?No. It is the JVM that determines when to pop the confirmation dialog.
    -With this being the case, can the applet now escape
    the sandbox, ..Assuming the end-user OK's the trust prompt, yes.
    ..be it with or without the stipulated
    policy permissions?Huh?

  • Java applet security file.list()

    I am trying to read the directory structure from a signed applet. I
    have created the applet and provided it with the
    UniversalFileAccess. I am able to read a specific file, and see all
    the contents of the file. I am wanting to performa simple
    directory listing vie the following code.
    My browser is Communictor 4.76 on Win 2000.
    blah.. blah...
    if(browser.indexOf("netscape") >= 0){
    //Assert Netscape permissions
    try{
    // tried UniversalFileRead, UniversalFileAccess,
    UniversalPropertyWrite,
    PrivilegeManager.enablePrivilege("UniversalFileRead");
    System.out.println("Netscape now has UniversalFileRead
    privilege.");
    } catch (netscape.security.ForbiddenTargetException e1) {
    System.out.println("Permission to read file system denied by
    user.");
    e1.printStackTrace();
    } catch(Throwable e){
    System.out.println("Could not enable privilege." +
    e.getMessage());
    e.printStackTrace();
    try {
    File f = new File("c:\\temp\\");
    String [] fileList = a.list();
    } catch (Throwable e) {
    System.out.println("File List failed");
    e.printStackTrace();
    I keep getting a secuity exception that I do not have priveledes to
    perform this action.
    Can anyone help!!!!!!!! I am on a deadline, and this is working just
    fine with IE.
    Please reply directly to me, as this is the first time I've ever posted
    to this newsgroup. My email is [email protected]
    Thanks,
    James Kurfees

    This question has been asked many times in these forums.
    There is no way to prevent this from a determined reverse engineer.
    Search for java obfuscators, which can help a little bit.
    The only way to prevent code stealing is to run it on your own server,
    which means not to use applets, but servlets/JSP. I am sure this is
    not what you want to hear.

  • Applet reading files in in web server eg geocities

    hi ,
    i have an applet that reads files i have created in a web server. when i try to run the applet in , internet explorer i get an error message
    java.io.FileNotFoundException: nic.txt (The system cannot find the file specified)
    does anyone have any solution to this problem. do i need a policy file and if i do where do i put it.

    Applets work on the clients computer, not the server. Your applet is >trying to read nic.txt from your computer. Can't be done easily, you'd >need your own serverprogram to do the reading and pass the data to the >client... let me clarify afew points
    the applet is on a webserver eg. geocities.
    the file is also on the same directory as the applet .class file.
    so everything is on the web server,.

  • Help with java applets

    Ok i know i haven't read the applet tutorial or had much experience with applets but just hear me out and see if you can help me.
    BACKGROUND
    Ok...so i have previously viewed an applet on windows viewing an html file on my computer. I am trying to view just the most simple applet (helloworld) on linux. I'm using Ubuntu linux, the latest version as of February 23, 2006.I created an applet file and an html file in the same directory with the html file having an <applet> tag in it linking to the HelloWorldApp. I have tried viewing the html file and the java applet won't load. Everything other than the applet worked and I'm just stuck.
    So my plea is would somebody please just paste the bare minimum html file and applet file that you can see an applet with? I want to learn about applets and will do the tutorial but I would really like to just see one.
    Please help,
    A frustrated applet noob
    p.s.
    According to java.com I have installed JRE 5.0 and i have compiled a java application so I'm pretty sure I have successfully installed JDK 5.0.

    Bob, what web browser are you using?
    Make sure that the browser supports Java applets.
    If you want just to debug your applet try appletviewer utility
    from JDK first.

  • Help with Java Applet Design

    Hi,
    I'm a uni student and I've had some programming experience in Java, although sadly a bit lacking in the area of Java Applets.
    Recently I've being involved in a project where some tests are ran a number of times and a Data Aquisition System is used to transfer the number of cycles the test have currently done onto the computer, in a .csv file.
    What I would like to do is to make this count available in a web browser LIVE.
    I've come up with an idea, which is to write a Java Applet to read this file and output the correct count value in a textbox or what ever, however I am having a bit of difficulty making this update live.
    Should I have some sort of script inside the webpage source that re-
    runs the applet at regular intervals? If then how would that be possible?
    Or should I have the applet re-read the file at regular intervals and repaint it-self? If then there will be problems with timers and possible execution threads (which I don't quite understand yet)?
    One thing I want to be careful of is that this file to be read is updated by the DAQ system at random times, so whatever solution is implemented, I wouldn't want the file to be corrupted (e.g. if the file is read and written at the same time).
    Thanks for any help

    Read data from file at regular specified intervals,
    display data in an applet.
    U can use java.util.Timer and TimerTask and schedule the task.
    for applets to read file, you may have have to sign the applet.
    public class ReadApplet{
    private Timer timer;
    private TimerTask tt;
    private JTextField tf;
    public void init(){
    tf=new JTextField(15);
    timer=new Timer();
    tt = new TimerTask(){
    public void run(){
    try{
    BufferedReader fr=new BufferedReader(new FileReader(datafile));
    String data = br.readLine();
    int num = Integer.parseInt( data);
    tf.setText("" + num);
    }catch(Exception e) {}
    timer.schedule( tt, 0, interval);
    - create a jar file containing the class file
    - generate a key using keytool -genkey
    - sign the applet jar with jarsigner -signedjar using your key
    -include applet code in html file
    <applet code="Yourapplet.class" ARCHIVE="your signed jar" width="" height=""></applet>
    It should work

  • Newbie help needed with Applet

    I am having a problem with the following Applet. I have highlighted it in bold.
    How can I ensure that all of the conditions are met regardless of the order they are inserted on the graph,within the program?
    At the moment I have to do them in the exact order they are in the code in order to get the "Winner" message.
    Also if I insert an image at any time at the point if(x >= 290 && x <= 350 && y >= 290 && y <= 350) I also receive the "Winner" message. I realise this happens because it is the last line of code in this statement.
    However I am very new to this and dont know how to fix it. Indeed I dont even know if this is the correct way to do this.
    Hope this makes sense.
    Any help would be very much appreciated
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class MyDraughts extends Applet implements MouseListener,ActionListener,
                   MouseMotionListener{
                        public MyDraughts(){
                             points = new ArrayList();
                             pawncount = 0;
                             pawncount1 = 14;
                             message = "";
                             message1 = "";
                             title = new Font ("Arial", Font.BOLD, 18);
         private Point square1, square2, square3, square4, square5, square6, square7,square8,square9,
         square10,square11,square12,square13,square14,square15,square16,square17,square18,square19,
         square20,square21,square22,square23,square24,square25,square26,square27,square28,square29,
         square30,square31,square32,mouse;
         private int select;
         private Image pawn;
         private Point icon;
         private ArrayList points;
         private int x;
         private int y;
         private int pawncount;
         private int pawncount1,pawncount2;
         private Button undoButton;
         private String message,message1;
         private Font title;
         public void init(){
              setBackground(new Color(210,255,210));
              this.addMouseMotionListener(this);
              this.addMouseListener(this);
              select = 0;
              square1=new Point(50,10);
              square2=new Point(130,10);
              square3=new Point(210,10);
              square4=new Point(290,10);
              square5=new Point(10,50);
              square6=new Point(90,50);
              square7=new Point(170,50);
              square8=new Point(250,50);
              square9=new Point(50,90);
              square10=new Point(130,90);
              square11=new Point(210,90);
              square12=new Point(290,90);
              square13=new Point(10,130);
              square14=new Point(90,130);
              square15=new Point(170,130);
              square16=new Point(250,130);
              square17=new Point(50,170);
              square18=new Point(130,170);
              square19=new Point(210,170);
              square20=new Point(290,170);
              square21=new Point(10,210);
              square22=new Point(90,210);
              square23=new Point(170,210);
              square24=new Point(250,210);
              square25=new Point(50,250);
              square26=new Point(130,250);
              square27=new Point(210,250);
              square28=new Point(290,250);
              square29=new Point(10,290);
              square30=new Point(90,290);
              square31=new Point(170,290);
              square32=new Point(250,290);
              undoButton = new Button("Undo");
    add(undoButton);
    undoButton.addActionListener(this);
              mouse= new Point();
              icon = new Point();
              pawn = getImage(getCodeBase(), "pawn.gif");
    public void actionPerformed(ActionEvent actionevent){
    if(actionevent.getSource() == undoButton){
    int a = points.size();
    int b = a - 1;
    points.remove(b);
    a = points.size();
    repaint();
    public void paint (Graphics g){
         drawBox(g);
         g.fillRect(square1.x, square1.y,40,40);
         g.fillRect(square2.x, square2.y,40,40);
         g.fillRect(square3.x, square3.y,40,40);
         g.fillRect(square4.x, square4.y,40,40);
         g.fillRect(square5.x, square5.y,40,40);
         g.fillRect(square6.x, square6.y,40,40);
         g.fillRect(square7.x, square7.y,40,40);
         g.fillRect(square8.x, square8.y,40,40);
         g.fillRect(square9.x, square9.y,40,40);
         g.fillRect(square10.x, square10.y,40,40);
         g.fillRect(square11.x, square11.y,40,40);
         g.fillRect(square12.x, square12.y,40,40);
         g.fillRect(square13.x, square13.y,40,40);
         g.fillRect(square14.x, square14.y,40,40);
         g.fillRect(square15.x, square15.y,40,40);
         g.fillRect(square16.x, square16.y,40,40);
         g.fillRect(square17.x, square17.y,40,40);
         g.fillRect(square18.x, square18.y,40,40);
         g.fillRect(square19.x, square19.y,40,40);
         g.fillRect(square20.x, square20.y,40,40);
         g.fillRect(square21.x, square21.y,40,40);
         g.fillRect(square22.x, square22.y,40,40);
         g.fillRect(square23.x, square23.y,40,40);
         g.fillRect(square24.x, square24.y,40,40);
         g.fillRect(square25.x, square25.y,40,40);
         g.fillRect(square26.x, square26.y,40,40);
         g.fillRect(square27.x, square27.y,40,40);
         g.fillRect(square28.x, square28.y,40,40);
         g.fillRect(square29.x, square29.y,40,40);
         g.fillRect(square30.x, square30.y,40,40);
         g.fillRect(square31.x, square31.y,40,40);
         g.fillRect(square32.x, square32.y,40,40);
         g.setFont(title);
         g.drawString(message, 350, 300);
         g.drawString(message1, 350, 320);
         for(int i = 0; i < points.size(); i++){
    icon = (Point)points.get(i);
    g.drawImage(pawn, icon.x, icon.y, 25, 25, this);
         g.drawImage(pawn,175,135,25,25,this);
         g.drawImage(pawn,135,175,25,25,this);
         g.setFont(title);
         g.drawString("Click A Square To Place A Pawn", 350, 50);
    public void mouseDragged(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
    //require for the interface
    public void mousePressed(MouseEvent mouseevent){
    setBackground(new Color(210,255,210));
    x = mouseevent.getX();
    y = mouseevent.getY();
    if(x > 19 && x < 312 && y > 19 && y < 312){
    pawncount = pawncount + 1;
    points.add(mouseevent.getPoint());
    if(pawncount > pawncount1){
    setBackground(Color.red);
    message = "Too Many Pawns!You can only place 14";
    message1 = "Hit restart to play again";
    pawncount1 = 14;
    if(x >= 10 && x <= 50 && y >= 290 && y <= 330){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    if(x >= 50 && x <= 90 && y >= 250 && y <= 290){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    if(x >= 90 && x <= 130 && y >= 210 && y <= 250){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    //This is the solution for the puzzle
    if(x >= 90 && x <= 130 && y >= 10 && y <= 50);
    if(x >= 250 && x <= 290 && y >= 10 && y <= 50);
    if(x >= 90 && x <= 130 && y >= 50 && y <= 90);
    if(x >= 170 && x <= 210 && y >= 50 && y <= 90);
    if(x >= 10 && x <= 50 && y >= 90 && y <= 130);
    if(x >= 50 && x <= 90 && y >= 90 && y <= 130);
    if(x >= 250 && x <= 290 && y >= 130 && y <= 170);
    if(x >= 50 && x <= 90 && y >= 170 && y <= 210);
    if(x >= 210 && x <= 250 && y >= 210 && y <= 250);
    if(x >= 290 && x <= 350 && y >= 210 && y <= 250);
    if(x >= 10 && x <= 50 && y >= 250 && y <= 290);
    if(x >= 130 && x <= 170 && y >= 250 && y <= 290);
    if(x >= 210 && x <= 250 && y >= 290 && y <= 350);
    if(x >= 290 && x <= 350 && y >= 290 && y <= 350){
    setBackground(Color.green);
    message = "Winner";
    pawncount = 14;
    repaint();
    //required for the interface
    public void mouseClicked(MouseEvent event){}
    public void mouseReleased(MouseEvent event){}
    public void mouseEntered(MouseEvent event){}
    public void mouseExited(MouseEvent event){}
    public void drawBox(Graphics g){
         for(int i=10;i<=350;i+=40){
    g.drawLine(i,10,i,330);
    g.drawLine(10,i,330,i);
    }

    Since your code is heavilly dependant on which square is clicked on I'd define a class extending JComponent to represent a square. You can make this an inner class, which would simplify access to other squares etc. Then lay these out in your JPanel, and each will have it's own paint method which will paint it with or without a pawn.
    At the same time you add all these as a two dimensional array for logical access. Each square has (or is) it's own mouseListener so that you can let awt figure out which you clicked on.
    private static final int CELL_SIZE=50;
    private static final int BOARD_SIZE= 8;
    private class Square extends JComponent implements MouseListener {
        public boolean hasPawn;
        private Square(int row, int col) {
             Rectangle where = new Rectangle(col * CELL_SIZE, row * CELL_SIZE,
    CELL_SIZE, CELL_SIZE);
            setBounds(where);
           addMousListener(this);
       public void addPawn() {
         if(!hasPawn) {
           hasPawn = true;
           repaint();
      public void paint(Graphics g) {
    } // end of inner class
    Square[][]board = new Square[BOARD_SIZE][BOARD_SIZE];}

Maybe you are looking for

  • Bridge CS4 always opens in the same folder

    Since I upgraded to Photoshop CS4, Bridge always opens in the same folder. It used to open up whatever folder I was working on last. There must be a setting somewhere to tell Bridge to open the last visited folder but I can't seem to find it. Any ide

  • BADI / User Exit after Saving of Business Partner

    Hi Experts, Is there a BADI / user exit that is triggered after saving / updating of Business Partner using transaction code "BP"? We want to send a XML file thru ALE after creation/modification of BP. We are using CRM WinClient 4.0. Thanks.

  • Looking to connect camcorder JVC GR-DA30U to iMac 27"

    Hey group! Wondering how I could connect my mini dv camcorder to my mac and transfer the video to the computer.  My camcorder only came with cord for playback on TV and the power cord, but nothing for the computer, especially a Mac.  The manual refer

  • What data base table we can find customer payments?

    I am using F-29 transaction and posting customer payments, can any one tell me what's the database table where we can see the amount posted. Example: If you are trying to pay $100.00 agnaist $1000.00. I need to know the database table where we can fi

  • DB Instance creation using DBCA Gives ERROR

    Hi All, I am getting below error while creating a new DB instance using DBCA. Initially I thought it could be a problem of the oracle version. But I checked it is Oracle 10G server version 10.2.0.1. I got it re-installed 3 times, but still same issue