Repaint in applet

hi
i've got an applet that draws an offset Image when mouse drag. now, when i minimize the browser
and restore it back, the offset image disappear and i need to draw it by mouse drag again.
what should i do to avoid the image to disappear?

Instead of drawing the image manually with a thread recode
class MyCanvas extends Canvas
Image image;
public canpan(Image img)
setBackground(Color.white);
image = img;
public void paint (Graphics g)
if (image == null)
return;
g.drawImage(image, 0, 0, this);

Similar Messages

  • Repaint() an applet from a swing applet, why does this code not work?

    below are three files that work as planned except for the call to repaint(). This is envoked when a button is hit in one applet and it should repaint another applet. I opened them up in a html file that simply runs both applets. If you could see why the repaint doesn't work I'd love to know. good luck.
    //speech1
    import java.awt.*;
    import java.applet.Applet;
    import java.awt.event.*;
    //java extension packages
    import javax.swing.*;
    public class speechapp1 extends JApplet implements ActionListener{
    // setting up Buttons and Drop down menus
    char a[];
    Choice choicebutton;
    JLabel resultLabel;
    JTextField result;
    JLabel enterLabel;
    JTextField enter;
    JButton pushButton;
    TreeTest PicW;
    // setting up applets G.U.I
    public void init(){
    // Get content pane and set it's layout to FlowLayout
    Container container = getContentPane();
    container.setLayout( new FlowLayout() );
    // initialise buttons and shit
    a = new char[30];
    choicebutton = new Choice();
    enterLabel = new JLabel("Test");
    enter = new JTextField(30);
    resultLabel= new JLabel("speech label");
    result = new JTextField(30);
    result.setEditable(false);
    // Add items to Choice Button
    choicebutton.addItem("abc");
    choicebutton.addItem("def");
    choicebutton.addItem("ghi");
    choicebutton.addItem("jkl");
    pushButton = new JButton("Click to continue");
    // Add new Tree from file TreeTest.java
    PicW = new TreeTest();
    // Add buttons to container.
    container.add(resultLabel);
    container.add(result);
    container.add(enterLabel);
    System.out.println("");
    container.add(choicebutton);
    System.out.println("");
    container.add(pushButton);
    pushButton.addActionListener(this);
    //choicebutton.addActionListener( this );
    // Set the text in result;
    result.setText("Hello");
    //public void paint(Graphics gg){
    // result.setText("Hello");
    public void actionPerformed(ActionEvent event){
    // continue when action performed on pushButton
    String searchKey = event.getActionCommand();
    System.out.println("");
    if (choicebutton.getSelectedItem().equals("abc"))
    PicW.getPicWeight(1);
    if (choicebutton.getSelectedItem().equals("def"))
    PicW.getPicWeight(2);
    if (choicebutton.getSelectedItem().equals("ghi"))
    PicW.getPicWeight(3);
    if (choicebutton.getSelectedItem().equals("jkl"))
    PicW.getPicWeight(4);
    System.out.println("repainting from actionPerformed method()");
    PicW.repaint();
    import java.applet.Applet;
    import java.awt.*;
    import java.util.*;
    public class TreeTest extends Applet{
    Tree BackgroundImageTree;
    Tree PlayerImageTree;
    Image snow,baby;
    int weight;
    public void getPicWeight(int w){
    weight = w;
    System.out.println("the new weight has been set at: "+weight);
    this.repaint();
    public void init()
    // initialising trees for backgound images and player images
    BackgroundImageTree = new Tree();
    PlayerImageTree = new Tree();
    // initialising images and correcting size of images to correctly fit the screen
    snow = getImage(getDocumentBase(),"snow.gif");
    baby = getImage(getDocumentBase(),"baby.gif");
    // inserting images into correct tree structure
    System.out.println("inserting images into tree: ");
    // inserting background images into tree structure
    BackgroundImageTree.insertImage(1,snow);
    // inserting players into tree structure
    PlayerImageTree.insertImage(1,baby);
    public void paint(Graphics g){
    System.out.println("Searching for selected Image");
    if((BackgroundImageTree.inorderTraversal(1)==null)&&(PlayerImageTree.inorderTraversal(1)==null)){
    System.out.println("There is no tree with the selected value in the trees");
    }else{
    g.drawImage(BackgroundImageTree.inorderTraversal(1),1,3,this);
    //g.drawImage(PlayerImageTree.inorderTraversal(1),55,150,this);
    import java.awt.*;
    import java.applet.Applet;
    class TreeNode {
    TreeNode left;
    Image data;
    TreeNode right;
    int value;
    public TreeNode(int weight,Image picture){
    left = right = null;
    value = weight;
    data = picture;
    public void insert(int v, Image newImage){
    if ( v< value){
    if (left ==null)
    left = new TreeNode(v,newImage);
    else
    left.insert(v,newImage);
    else if (v>value){
    if (right ==null)
    right = new TreeNode(v,newImage);
    else
    right.insert(v, newImage);
    public class Tree{
    private TreeNode root;
    public Tree() {
    root = null;
    public void insertImage(int value, Image newImage){
    if (root == null)
    root = new TreeNode(value,newImage);
    else
    root.insert(value,newImage);
    // in order search of tree.
    public Image inorderTraversal(int n)
    return(inorderHelper(root,n));
    private Image inorderHelper(TreeNode node, int n){
    Image temp = null;
    if (node == null)
    return null;
    if (node.value == n ){
    return(node.data);
    temp = inorderHelper(node.left,n);
    if (temp == null){
    temp = inorderHelper(node.right,n);
    return temp;
    }

    I can fix your problems
    1. You get an error here because you can only invoke the superclass's constructor in the subclass's constructor. It looks like that's what you're trying to do, but you're not doing it right. Constructors don't return any value (actually they do, but it's implied, so you don't need the void that you've got in your code)
    2. I'm not sure, but I think your call to show might be wrong. Move the setsize and setvisible calls to outside of the constructor

  • Problem to repaint my applet

    Hi,
    I am developping an applet that owns several interface. So I have an interface Identificator and another Registrator.
    During the init() phase of my applet I create my Panel object Identificator, and I display it.
    When I click on the button register (contained in Identificator), I create my new Panel Object Rgistrator, and I try to display it.
    First I remove the Identificator Panel of the Applet's Container and I add the Registrator Panel to it.
    After that I lauch the method repaint().
    After that nothing is displayed, but if I resize my Browser Window, my interface Registrator is displayed!!!!!!!!
    Is there someone that could help me...
    Thank you very much...

    maybe the setVisible(true) operator may work,. I know that when I forget this in a JFrame my frame won't show.
    Greetings,.
    Arnoud

  • Convert applet to swing

    Hi;
    Could anyone help me to convert my example code from applet to swing,please, thank
    import java.awt.*;
    import java.applet.*;
    import java.lang.Math;
    import java.awt.Font;
    import java.lang.Integer;
    /*** Main class == Applet  ***/
    public class Suffix extends Applet implements Runnable {
       private Thread main;
       public s_tree _tree=null;
       public node nd=null;
       public boolean userPause=false,resumed=false;
       private String str[]={"GOOGOL$","Paused","Resumed","Compacting","Done"};
       public Color bl=Color.blue,rd=Color.red;
       public Font fnt;
       public int mode=3,delay=3000;
       private char alph[]={'$','Q','W','E','R','T','Y','U','I','O',
                        'P','A','S','D','F','G','H','J','K','L',
                        'Z','X','C','V','B','N','M'};
    /*** initialisation function. It is the first Funct to be called ***/
       public void init() {
    // Temp data
          int temp=0,nxx=30;
    // Ini. of fnt , the font size + style used by this applet.
          fnt=new Font("Denis",1,25);
    /*** parsing command parameters ***/
    //      try {
    //DELAY VALUE PARAM
             String param=getParameter("DELAY");
             if (param!=null) {
                temp=Integer.parseInt(param);
                if ((temp>500)&&(temp<6000)) delay=temp;
    //x LEFTMOST coordinate
             param=getParameter("X");
             if (param!=null) {
                temp=Integer.parseInt(param);
                nxx=temp;
    //Base String parameter
             param=getParameter("STRING");
             if ((param!=null)&&(param.length()<15)) {
                str[0]=param;
    //      } catch (ParseException e) { showParseError(e); }
    // Allocating mem for _tree + initialize it .
          _tree=new s_tree(str[0],fnt);
    // Override xx (left_bound) by the caller's or the default value
          _tree.xx=nxx;
    /*** "animation loop is controled here" ***/
       public void run() {
         while(true) {
             try {
    //delay the process for time==delay
                Thread.sleep(delay);
             } catch (InterruptedException e) {}
    //controls animation loop
          repaint();
    /*** override APPLET's paint function ***/
       public void paint (Graphics g) {
    //Output graphics
          update(g);
    /*** Updates the graphics ***/
       public void update (Graphics g) {
    // Set font
          if (g.getFont()!=fnt) g.setFont(fnt);
          if ((userPause==false)&&(resumed==false)) // Is the applet paused ?
             g.clearRect(0,0,1024,768); //clears the screen
             if (_tree==null) {     // if tree is not initialised
                init();
                //_tree.show(g);
             } else {
                if (mode==3) {      // if graphics output mode is 3
                   if (nd!=null) nd._to_rd(false);
                   nd=_tree.step_compact(nd);  //compacts the tree one step further
                   if (nd==null)  // if tree is totally compacted ...
                      mode=4;   //change the ani. mode to 4 (don't call compact)
                   else
                      nd._to_rd(true);  //colors the next node to compact in red
    // Draw the "titleviewport's" comment
             g.setColor(bl);
             g.drawString(str[mode],10,15);
             _tree.show(g);     //show tree
          } else {
             g.clearRect(0,0,200,25);  //clears the "titleviewport to update it"
             g.setColor(rd);
             if (resumed==true){
                resumed=false;
                g.drawString(str[2],10,15);
             else g.drawString(str[1],10,15);
    /*** restart the animation process ***/
       public void start() {
          main=new Thread(this);
          main.start();
    /*** stops the animation ***/
       public void stop() {
          main.stop();
          main=null;
    /*** Handles the user's events (mouse , kbd , ... ***/
       public boolean handleEvent(Event evt) {
          if (evt.id==Event.MOUSE_DOWN) { //if mouse button have been pushed ...
                if (main!=null && main.isAlive()) {
                   if (userPause) {
                      main.start();
                      resumed=true;
                   } else {
                      main.stop();
                   userPause= !userPause;
                } else {
                   main= new Thread(this);
                   main.start();
                   userPause=false;
                   resumed=true;
                repaint();
             return true;
          } else {
             return super.handleEvent(evt);
    /*** Linked List of node(s) ***/
    class nodelist{
       nodelist next=null;
       node ptr=null;
       public void nodelist(){};
    /*** node of a structure tree ***/
    class node {
    // Relatives
       public nodelist children=null;
       public node parent=null;
    // variables
       public int maxchild=12,childnum=0,level=0;
       public int center[]={0,0};
       public int xlen=20,ylen=10,vspace=15,hspace=8;
       public int x[]={0,0};
       public boolean _ishidden=false;
       private Color bk=Color.black,wh=Color.white,rd=Color.red;
    // Node==red toggle variable
       public boolean to_rd=false;
    // node's text
       public String label=null;
    /*** initialisation of the node ***/
       public node(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,String nstr){
          x[0]=nx; x[1]=ny;
          xlen=nxl; ylen=nyl;
          parent=nparent;
          level=nlevel;
          label=new String(nstr);
          children=new nodelist();
    /*** destroys the node ***/
       public void destruct() {
    // NOTE : not like C++ destructors . Do not confuse .
          delete_subtree();
          children=null;
          parent=null;
          bk=wh=rd=null;
          label=null;
    /*** Node to red toggle switch ***/
       public void _to_rd(boolean b) {to_rd=b;};
    /*** Adds a child to this node ***/
       public void add_child(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,
                                String nstr) {
          if (childnum<maxchild) {    // if 'legal' space left ...
             if (children==null) {    // if no nodelist attached ...
                children=new nodelist(); //init. children
                children.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr); //create node
                childnum++;
             } else {
                nodelist dummy=children;
    // search for the last nodelist
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist(); //adds a nodelist
                dummy=dummy.next;
                dummy.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr); //create child
                childnum++;
    // Tree needs to be realigned
    /*** adds a child and returns its address ***/
       public node add_child_ret(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,
                                String nstr) {
          if (childnum<maxchild) {
             if (children==null) {
                children=new nodelist();
                children.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr);
                childnum++;
                return(children.ptr);
             } else {
                nodelist dummy=children;
    // search for the last child
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist();
                dummy=dummy.next;
                dummy.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr);
                childnum++;
                return(dummy.ptr);
        return(null);
    // Tree needs to be realigned
    /*** adds the node nchild as a new children ***/
       public void add_child(node nchild) {
          nodelist dummy=null;
          dummy=children;
          if (childnum<maxchild) {
             if (children==null) {
                children=new nodelist();
                children.ptr=nchild;
                childnum++;
             } else {
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist();
                dummy=dummy.next;
                dummy.ptr=nchild;
                childnum++;
    //Tree needs to restructured.
    /*** deletes all childrens ***/
       public void delete_subtree() {
          while (childnum>0 && children!=null) { //while child exists , kill it
             if (children.ptr!=null) {
                children.ptr.destruct();
                children.ptr=null;
                children=children.next;
             } else children=null;
             childnum--;
    /*** moves this node and its children horizontally ***/
       public void move_tree(int nx) {
          nodelist dummy=children;
          x[0]+=nx;
          while (childnum>0 && dummy!=null) {
             if (dummy.ptr!=null) {
                dummy.ptr.move_tree(nx);
                dummy=dummy.next;
    /*** removes the node from the tree (do not preserve order of ordered tree ) ***/
       public void remove_node() {
          nodelist dummy=children;
          while(dummy!=null) {
             if (dummy.ptr!=null){
                parent.add_child(dummy.ptr);
             dummy=dummy.next;
          children=null;
    //could call restructure tree here .
    //don't forget to change the node's levels !!!
    /*** show all nodes ***/
       public void show_all(Graphics g) {
          if (_ishidden==false) { //if not hidden
             if (children!=null) {  //if child exist
                nodelist dummy=children; //temp var.
                while(dummy!=null) { //while there is a child...
                   if (dummy.ptr!=null)
                      dummy.ptr.show_all(g);
                   dummy=dummy.next;
             show_node(g);
    /*** show nodes in preorder ***/
       public int preorder_show(Graphics g,int label){
          if (_ishidden==false) {
             show_node(g/*,label++*/);
             if (children!=null) {
                nodelist dummy=children;
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.preorder_show(g,label);
                   dummy=dummy.next;
          return(label);
    /** show nodes in postorder ***/
       public int postorder_show(Graphics g,int label){
          if (_ishidden==false) {
             if (children!=null) {
                nodelist dummy=children;
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.postorder_show(g,label);
                   dummy=dummy.next;
             show_node(g/*,label++*/);
          return(label);
    /*** show nodes in inorder ***/
       public int inorder_show(Graphics g,int label){
          if (_ishidden==false) {
             if (children!=null) {
                nodelist dummy=children;
                if (dummy.ptr!=null) label=dummy.ptr.inorder_show(g,label);
                dummy=dummy.next;
                show_node(g/*,label++*/);
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.inorder_show(g,label);
                   dummy=dummy.next;
             } else show_node(g/*,label++*/);
          return(label);
    /*** Restructure the coordinates of all nodes ***/
       public int align(int min,Font fnt,int lev,Graphics g){
          int i=min; //left bound
          FontMetrics fntm=g.getFontMetrics(fnt); //used to know the text size
          level=lev;
    // node x and y radius are computed here
          xlen=4+(int)(fntm.stringWidth(label)/2);
          ylen=4+(int)(fntm.getHeight()/2);
          if (children!=null) {      //if child present ...
             nodelist dummy=children;
             while(dummy!=null) {
                if (dummy.ptr!=null) i=dummy.ptr.align(i,fnt,lev+1,g); //align them
                   dummy=dummy.next;
          x[0]=min+(int)((i-min)/2); //could be underflow so will be checked
          x[1]=lev*(vspace+(ylen*2))+26;
    // overflow should happen only when the parent node is larger than its children
          if ((x[0]-xlen)<min) { //check uf underflow occurs.
             move_tree(min+xlen-x[0]+1);
             i=x[0]+xlen+5;
          if (childnum==0) x[0]+=2;
        return(i);
    /*** returns the child following nd ***/
    /*** if nd==null -> return 1st child ***/
    /***  if nd==last children -> return null***/
       public node next_child(node nd) {
          nodelist dummy=null;
          if (children==null) return(null);
          if (nd==null) return(children.ptr);
          dummy=children;
          while (dummy.ptr!=nd) {
             if (dummy.next!=null)
                dummy=dummy.next;
             else
                return(null);
          dummy=dummy.next;
          if (dummy!=null) return(dummy.ptr);
             else return(null);
    /*** returns child with first letter==nh ***/
       public node get_childd(char ch) {
          nodelist dummy=null;
          dummy=children;
          while (dummy!=null) {
             if (dummy.ptr!=null) {
                if (dummy.ptr.label.charAt(0)==ch)
                   return(dummy.ptr);
             dummy=dummy.next;
        return(null);
    /*** returns the nodelist containing nd ***/
       public nodelist get_child(node nd) {
          nodelist dummy=children;
          while (dummy!=null) {
             if (dummy.ptr==nd) return(dummy);
             dummy=dummy.next;
        return(null);
    /*** outputs the node to Screen ***/
       public void show_node(Graphics g) {
          if (_ishidden==false) {
             if (level>0) {  //if it is not a root then draw link-line
                g.setColor(bk);
                g.drawLine(x[0],x[1]-ylen,parent.x[0],parent.x[1]+parent.ylen); //from this node to parent node
             if (to_rd==false)
                g.setColor(wh);
             else
                g.setColor(rd);
             g.fillOval(x[0]-xlen,x[1]-ylen,xlen*2,ylen*2); //draws an oval
             g.setColor(bk);
             g.drawString(label,x[0]-xlen+4,x[1]+ylen-12);  //output the text
    /*** class which uses nodes to create a SUFFIX TREE ***/
    class s_tree {
       node root=null;    // root node.
       String str=null;   // 'search' string
       Font fnt=null;     // font type
       int xx=30;         // left limit for graphics
    /*** initialize a SUFFIX TREE with string==nstr and Font==nfnt ***/
       public s_tree(String nstr,Font nfnt) {
          str=new String(nstr);
          fnt=nfnt;
          create();
    /*** uninitialize the structure **/
       public void destruct() {
          root.destruct();
          str=null;
          fnt=null;
    /*** show the tree ***/
       public void show(Graphics g) {
          root.align(xx,fnt,0,g);   // restructure node's coordinates
          root.show_all(g); //show tree
    /*** creates a tree structure from String=str ***/
       public void create() {
          node dummy=null;
          root=new node(0,0,0,0,dummy,0," "); //create root
          root.parent=null; //just to make sure ...
          for (int i=0;i<str.length();i++) {
    // Create subtree of root in the following way :
    //    create subtree ("ASDF$");
    //        "     "    ("aSDF$");
    //       "    "      ("asDF$"); ...
    // where : the UPPERCASE letters is the part of the string sent to insert_string
             insert_string(str.substring(i));
          //root.align(0,fnt,0); //align root now ?
    /*** creates a subtree of ROOT with String=nstr ***/
       public void insert_string(String nstr) {
          node dummy2=null,dummy=null;
          int i=0;
          dummy=root;
          dummy2=root;
    // As long as a children of dummy2 have the letter nstr[i] , dummy==thischildren
    // It is used to make sure that a node does not have two children with the
    // same letter
          while (dummy2!=null) {
             dummy2=dummy2.get_childd(nstr.charAt(i));
             if (dummy2!=null) {
                i++;
                dummy=dummy2;
    //create the nodes for the rest of the string
          for(;i<nstr.length();i++) {
             if (dummy!=null) dummy=dummy.add_child_ret(0,0,0,0,dummy,1,nstr.substring(i,i+1));
    // Compacts the tree node by node and returns the next node to compact
    // if node==null , compacts the first node ...
    //Works in POST-ORDER
       public node step_compact(node nd) {
          node dummy=nd,dummy2=null;
          nodelist ndlst=null;
    // GOES TO THE LOWER LEFT CHILDREN
          if (nd==null) { //first call !
             dummy=root;
             while(dummy.children!=null) {
                if (dummy.children.ptr==null)
                   dummy.children=dummy.children.next;
                else
                   dummy=dummy.children.ptr;
    //*** tries to find a 'compactable' node ***
    //*** It uses the POST-ORDER method      ***
    // if this node is not the last children then try to find next compactable node
    // in the next children.
          if (dummy.parent.childnum!=1) dummy=next_chain(dummy);
          if (dummy==null) return(null); //fully optimized
    //remove parent node.
    /*** THIS IS WHERE COMPACTING TAKES PLACE  **/
          dummy2=dummy.parent.parent;
          ndlst=dummy2.get_child(dummy.parent);
          if (ndlst==null) return(null); //we've got a beeeeg problem if this happens ...
    //*** merges the parent string with this one and delete parent .
          dummy.label=dummy.parent.label.concat(dummy.label);
          ndlst.ptr=dummy;
          //delete parent .
          dummy.parent=null;
          dummy.parent=dummy2;
    //      root.align(0,fnt,0);
        return(dummy);
    /*** finds the next chain in the tree (i.e. the next compactable node) ***/
       public node next_chain(node nd){
          node dummy=null;
          if (nd.parent==null) return(null); //finished ! This is the root
          if (nd.parent.childnum==1) return(nd); //can be optimized
    // finds the nd.parent's child following nd
          dummy=nd.parent.next_child(nd);
          if (dummy==null)  // if OLD_nd==last child
             return(next_chain(nd.parent));      //tries to find a chain upwards
          else {
                 // OLD_nd was not the last child . nd==OLD_nd's next brother
    // GOES TO THE LOWER LEFT most child of nd's subtree.
             while(dummy.children!=null) {
                if (dummy.children.ptr==null)
                   dummy.children=dummy.children.next;
                else
                   dummy=dummy.children.ptr;
             return(next_chain(dummy)); // returns the next compactable node
    };

    First, show me the rupees! Show me the rupees!

  • Animated gifs in applets

    Ive tried to display an animated gif in an applet and it only shows the first frame. What is the code to do this and it be animated?

    IIRC, every time you repaint the applet that contains the gif, the correct frame of the (multi-frame, animated) gif will be rendered.
    So if you create a thread that just calls repaint() every half-second or so, you should see the gif move.
    Usually it isn't necessary to do this explicitly, because there's already a thread updating state and repainting, for some other purpose.

  • Why is my applet hanging?

    Can anyone give me some insight as to why my applet is hanging? I just get the grey rectangle and no output in the java plugin console as to any kind of errors. I think it may have to do with hte ContentPane in both the main() and init() but I am not sure. I have been struggling with this problem for a couple of days now and I am not sure how to resolve it. Thanks in advance
    import java.awt.*;
    import java.lang.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.image.*;
    import javax.swing.text.*;
    import com.tpg.base.MileMessages;
    public class BlackBoxUIApplet extends JApplet implements ActionListener{
         public static int WIDTH = 800;
         public static int HEIGHT = 450;
         private boolean inAnApplet = true;
         //public static String TITLE = "Turnpike BlackBoxUI";
         //public static String input;
         Container frameContainer;
         JPanel[] panels = new JPanel[4];
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu("File");
         JMenuItem fileExit = new JMenuItem("Exit");
         //Icon openIcon = new ImageIcon("C:\\Dave\\Java Swing\\open.gif");
         JLabel statusLabel = new JLabel();
         //Icon statusIcon = new ImageIcon("flashing_red_button.gif");
         JButton pushButton1 = new JButton("Process File");
         JButton pushButton2 = new JButton("Process Folder");
         JButton pushButton3 = new JButton("One More Button");
         JButton openButton = new JButton("Open a File");
         //JLabel pbLabel = new JLabel("Processing.....");
         JTextArea textArea = new JTextArea(30,90); //rows,cols
         JScrollPane areaScrollPane = new JScrollPane(textArea);          
         JTextField inputFile = new JTextField(32);
         JTextField status = new JTextField(20);
         JTextField status1 = new JTextField(20);
         //JProgressBar pb = new JProgressBar();
         PipedInputStream piOut;
    PipedOutputStream poOut;
         String inputValue;
         MileMessages messages;
         //pb.setIndeterminate(true);
         //to avoid message about system event access
         public BlackBoxUIApplet() throws IOException
              this(true);
         //public BlackBoxUIApplet(boolean inAnApplet)
         public BlackBoxUIApplet(boolean inAnApplet) throws IOException
         //super(TITLE);
         //input = inputValue;
         this.inAnApplet = inAnApplet;
              if(inAnApplet)
                   getRootPane().putClientProperty("defeatSystemEventQueueCheck",
                                                                                              Boolean.TRUE);
                   // Set up System.out
    piOut = new PipedInputStream();
    poOut = new PipedOutputStream(piOut);
                        messages = new MileMessages();
    System.setOut(new PrintStream(poOut, true));
                        // Create reader threads
    new ReaderThread(piOut).start();
         public void init()
         setContentPane(buildGUI());
         //addWindowListener(new WindowHandler());
         fileExit.addActionListener(new MenuItemHandler());
         pushButton1.addActionListener(this);
         pushButton2.addActionListener(this);
         pushButton3.addActionListener(this);
         openButton.addActionListener(this);
         //setupEventHandlers();
         setSize(WIDTH, HEIGHT);
         setBackground(Color.darkGray);
         inputValue = JOptionPane.showInputDialog("Please input your ctxURL: (eg. //localhost:8080/main/InboundXMLServlet)");
         messages.runMilesMessages(inputValue);
         //show();
         public void actionPerformed(ActionEvent e)
              String cmd = e.getActionCommand();
              System.out.println("Command is: " + cmd);
              if(cmd.equals("Process File"))
                   textArea.append("I am processing!" + "\n");
                   System.out.println("ctxURL is: " + inputValue);
                   //status.setText("Currently processing " + inputValue + "....");
              else if(cmd.equals("Open a File"))
                        //final JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir"))); //goes up two levels from invoking directory
                        //final JFileChooser fc = new JFileChooser("../.."); //goes up two levels from invoking directory
                        final JFileChooser fc = new JFileChooser("../..");
                        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                        int returnVal = fc.showOpenDialog(this);
                        if (returnVal == JFileChooser.APPROVE_OPTION)
                             File file = fc.getSelectedFile();
                             inputFile.setText(file.getPath());
              else if(cmd.equals("Process Folder"))
              else if(cmd.equals("One More Button"))
         public Container buildGUI()
              setupMenuBar();
              Container tempContainer = layoutComponents();
              return (tempContainer);
         void setupMenuBar()
              fileMenu.add(fileExit);
              menuBar.add(fileMenu);
              setJMenuBar(menuBar);
         public Container layoutComponents()
              for(int i=0; i<panels.length;++i)
                   panels[i] = new JPanel();
                   panels[0].setBorder(new TitledBorder("Push Buttons"));
                   //panels[0].setBorder(BorderFactory.createEtchedBorder());
                   panels[0].setLayout(new FlowLayout(1, 10, 90)); //center with horz gap of 10 and vert gap of 60
                   //panels[0].setLayout(new BorderLayout());
                   //panels[0].setLayout(new GridLayout(3,1));
                   //use setPreferredSize(Dimension) to change size of each panel
                   //panels[0].setAlignmentX((float) 20);
                   pushButton1.setMargin(new Insets(5,10,5,10));
                   pushButton1.setVerticalTextPosition(AbstractButton.CENTER);
                   pushButton1.setHorizontalTextPosition(AbstractButton.LEFT);
                   pushButton1.setToolTipText("Process a File");
                   pushButton2.setMargin(new Insets(5,10,5,10));
                   pushButton2.setVerticalTextPosition(AbstractButton.CENTER);
                   pushButton2.setHorizontalTextPosition(AbstractButton.LEFT);
                   pushButton2.setToolTipText("Process a Folder");
                   pushButton3.setMargin(new Insets(5,10,5,10));
                   pushButton3.setVerticalTextPosition(AbstractButton.CENTER);
                   pushButton3.setHorizontalTextPosition(AbstractButton.LEFT);
                   pushButton3.setToolTipText("Tip3");
                   //panels[0].add(Box.createVerticalStrut(2));
                   panels[0].add(pushButton1);
                   //panels[0].add(pushButton1, BorderLayout.NORTH);
                   //panels[0].add(Box.createVerticalStrut(2));
                   panels[0].add(pushButton2);
                   //panels[0].add(pushButton2, BorderLayout.CENTER);
                   //panels[0].add(Box.createVerticalStrut(2));
                   panels[0].add(pushButton3);
                   //panels[0].add(pushButton3, BorderLayout.SOUTH);
                   panels[1].setBorder(new TitledBorder("Status"));
                   panels[1].setLayout(new FlowLayout(1,10,60));
                   //panels[1].setBorder(BorderFactory.createEtchedBorder());
                   //panels[1].setLayout(new GridLayout(2,1));
                   status.setEditable(false);
                   status1.setEditable(false);
                   //statusLabel.setIcon(statusIcon);
                   panels[1].add(statusLabel);
                   status.setText("Server is OK.");
                   status1.setText("File is OK.");
                   panels[1].add(status);
                   panels[1].add(status1);
                   //panels[1].add(pbLabel);
                   //pb.setIndeterminate(true);
                   //panels[1].add(pb);
                   //pb.setValue(0);
                   //pb.setStringPainted(true);
                   panels[2].setBorder(new TitledBorder("File Input"));
                   //panels[2].setBorder(BorderFactory.createEtchedBorder());
                   //panels[2].setLayout(new BoxLayout(panels[2], BoxLayout.X_AXIS));
                   panels[2].setLayout(new FlowLayout(1,50,20));
                   //panels[2].setLayout(new GridLayout(1,2));
                   //panels[2].add(Box.createHorizontalStrut(5));
                   panels[2].add(inputFile);
                   //panels[2].add(Box.createVerticalStrut(5));
                   panels[2].add(openButton);
                   //panels[2].add(Box.createHorizontalStrut(15));
                   panels[3].setBorder(new TitledBorder("Output"));
                   //panels[3].setBorder(BorderFactory.createEtchedBorder());
                   panels[3].setLayout(new GridLayout(1,1));
                   textArea.setFont(new Font("Serif", Font.PLAIN, 16));
                   textArea.setMargin(new Insets(5,5,5,5));
                   textArea.setLineWrap(true);
                   textArea.setWrapStyleWord(true);
                   textArea.setEditable(false);
                   areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                   areaScrollPane.setPreferredSize(new Dimension(50, 50));
                   panels[3].add(areaScrollPane);
                   frameContainer = getContentPane();
                   frameContainer.setLayout(new GridLayout(2,2));
                   //frameContainer.setLayout(new FlowLayout());
                   for(int i=0;i<panels.length;++i)
                        frameContainer.add(panels);
                        //frameContainer.add(Box.createHorizontalStrut(5));
                   return (frameContainer);
         //void setupEventHandlers()
              //addWindowListener(new WindowHandler());
              //fileExit.addActionListener(new MenuItemHandler());
              //pushButton1.addActionListener(new ButtonHandler());
              //pushButton2.addActionListener(new ButtonHandler());
              //pushButton3.addActionListener(new ButtonHandler());
              //openButton.addActionListener(new OpenHandler());
              //inputFile.setActionCommand(textFieldString);
              //inputFile.addActionListener(new TextHandler());
              //cmdField.addAncestorActionListener(new TextAreaHandler());
              //status.addAncestorActionListener(new TextAreaHandler());
         public static void main(String[] args)
              JFrame frame = new JFrame();
              frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
              try
                   BlackBoxUIApplet app = new BlackBoxUIApplet(true);
              frame.setContentPane(app.buildGUI());
              frame.pack();
              frame.setVisible(true);
              catch (IOException e)
         public class MenuItemHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   String cmd = e.getActionCommand();
                   if(cmd.equals("Exit")) System.exit(0);
         class ReaderThread extends Thread {
    PipedInputStream pi;
    ReaderThread(PipedInputStream pi) {
    this.pi = pi;
    public void run() {
    final byte[] buf = new byte[1024];
    try {
    while (true) {
    final int len = pi.read(buf);
    if (len == -1) {
    break;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    textArea.append(new String(buf, 0, len));
    // Make sure the last line is always visible
    textArea.setCaretPosition(textArea.getDocument().getLength());
    // Keep the text area down to a certain character size
    int idealSize = 100000;
    int maxExcess = 500;
    int excess = textArea.getDocument().getLength() - idealSize;
    if (excess >= maxExcess) {
    textArea.replaceRange("", 0, excess);
    } catch (IOException e) {

    I think I figured out why the applet is hanging. It is right after I call messages.MileMessage(inputValue). That method search the drive for a certain file type. the only problem is that I want to repaint the applet after that method is called and I don't understand how the method is called before I input hte "inputValue" variable! Is there any way to stall the method call until after everything is painted and the inputValue is entered? Sorry, but you hve to look to the previous post for the code.
    -Dave

  • Applet doesn't takeup the new file until browser is started again

    Hi Friends
    I have made a applet which can record and also can play the .wav file.
    I am using java sound api.
    But when I run this applet and record the sound and then click a button to play it , it plays the older file. But after recording, the older file got replaced with the new file, then why it plays the older. It should now play the new file.
    But after closing the IE browser and starting it again plays the newer recorded fle. Refreshing applet doesn't work.
    I have checked this also on firefox browser, same is happening.
    I have also tried to solve this problem using threading, but could not succeed. In threading I made AudioClip object null and reassigned the value in run method of the thread.
    Please solve this problem.
    Thanks

    I've found that the render error is due to the applet being hidden/displayed via JavaScript. Now that I've played around with that, I find it a highly unrecommendable approach. Basically what's done is:
    <div id="foo">
    <applet id="myapplet" ...>
    </applet>
    </div>
    <script>
    document.getElementById('foo').style.visibility = 'hidden';
    document.getElementById('foo').style.visibility = 'visible';
    document.getElementById('myapplet').repaint();
    </script>
    The "repaint" call does call the repaint method in the applet, but the result is the sad picture that I've linked to.
    Anyone know a robust way to repaint an applet from JavaScript?

  • ERROR in my applet program

    When I execute my applet, it gives me this error:
    Exception in thread "main" java.lang.NoSuchMethodError: main
    However when it runs in the appletviewer fine. Heres the code:
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
    public class slideshow extends Applet implements Runnable
            //creates the main thread
         Thread mainthread=null;
         //the amount of sleep time for the thread
         int time=2000; //milliseconds
            int x=1;
            int numberofimages=5; //this variable is needed since the paint function will know how many
            private Image bgimage1;
            private Image bgimage2;
            private Image bgimage3;
            private Image bgimage4;
            private Image bgimage5;
            String parameter;
         public void init()
                    parameter = getParameter("totalimages");
                    int numimages = (parameter==null? 0:Integer.parseInt(parameter));
                    numberofimages=numimages;//setting the global to this value
                    String imagename = getParameter( "name" );
                    String imagename2 = getParameter( "name2" );
                    String imagename3 = getParameter( "name3" );
                    String imagename4 = getParameter( "name4" );
                    String imagename5 = getParameter( "name5" );
                    bgimage1=getImage(getDocumentBase(), imagename);
                    bgimage2=getImage(getDocumentBase(), imagename2);
                    bgimage3=getImage(getDocumentBase(), imagename3);
                    bgimage4=getImage(getDocumentBase(), imagename4);
                    bgimage5=getImage(getDocumentBase(), imagename5);
              //constructs the thread
              mainthread=new Thread(this);
              //starts the thread
              mainthread.start();
        public void run(){
              while(mainthread!=null)
                    {try{
                  //makes the thread sleep
                  mainthread.sleep(time);
              catch(Exception e){}
              //repaints the applet
              repaint();
        public void stop()
              if(mainthread!=null){mainthread.stop();}
        public void paint(Graphics g)
                if (x==1)
                   g.drawImage(bgimage1,0,0,getWidth(),getHeight(),this);
                   //draws image the full size of the applet
                if (x==2)
                   g.drawImage(bgimage2,0,0,getWidth(),getHeight(),this);
                if (x==3)
                   g.drawImage(bgimage3,0,0,getWidth(),getHeight(),this);
                if (x==4)
                   g.drawImage(bgimage4,0,0,getWidth(),getHeight(),this);
                if (x==5)
                   g.drawImage(bgimage5,0,0,getWidth(),getHeight(),this);           
                x++;
                if (x>numberofimages)
                   x=1; 
    //end     
    }     

    When you say "execute" do you mean you are trying to launch your Applet as an application like:
    java slideshow
    That won't work because your code is only an Applet. When you invoke a class with the java.exe command, you need a main method and your code doesn't have one. You'll also need to explicitly call init() and run(), and you'll need to provide a Frame to hold your Applet.

  • Painting in applets

    I ran into a problem using AWT in applets. Sometimes in IE the animated applets repaints in a random place. Sometimes it's taskbar area, sometimes browsers toolbar. I don't know if it's JRE 1.3.1_08's bug or it may be code's fault.
    Anyone ran into similar issue?

    Thanx Foxy Lady ;), but he problem occurs more often in an applet like this. Simple ticker with double buffering. I think the problem is in refreshing the applet more often than one second. Here's the code:
    import java.applet.Applet;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.FontMetrics;
    import java.awt.Image;
    public class Ticker extends Applet implements Runnable {
         * Whole text to draw.
        String text = new String();
         * Single line from the script.
        String line;
         * Speed of moving text.
        int delay;
         * Background color.
        int bgColor;
         * Foreground color.
        int color;
         * Flag indicating if this applet is still active.
        boolean flag = true;
        int i = 0;
         * Offscreen image for doublebuffering.
        Image offscreenImage;
         * Width of the whole text.
        int textWidth;
         * Width of the applet.
        int wdth;
         *  The initialization method - getting parameters from the script.
        public void init() {
            line = new String(getParameter("text"));
            bgColor = Integer.parseInt(getParameter("bgColor"), 16);
            color = Integer.parseInt(getParameter("color"), 16);
            delay = Integer.parseInt(getParameter("delay"));
            wdth = Integer.parseInt(getParameter("width"));
            setBackground(new Color(bgColor));
            setSize(wdth, 20);
            offscreenImage = createImage(wdth, 20);
        public void paint(Graphics g) {
            drawText(i, g);
         * Draws the text in the <code>iks</code> position.
         * @param iks position of the text.
         * @param gr graphics context.
        public void drawText(int iks, Graphics gr) {
            gr.setColor(new Color(color));
            gr.setFont(new Font("SansSerif", Font.BOLD, 15));
            if (iks < -(textWidth - wdth)) {
                //if the whole text went away to the left
                //we should draw it from the beginning
                gr.drawString(text, iks + textWidth, 15);
            gr.drawString(text, iks, 15);
        public void update(Graphics g) {
            //getting the offscreen graphics context
            Graphics offscreenG = offscreenImage.getGraphics();
            //clearing the offscreen
            offscreenG.clearRect(0, 0, wdth, 20);
            //drawing the text in the offscreen
            paint(offscreenG);
            //replacing the screen with a ready offscreen image
            g.drawImage(offscreenImage, 0, 0, this);
        public void run() {
            Graphics g = getGraphics();
            FontMetrics metrics;
            //preparing the text to show
            g.setFont(new Font("SansSerif", Font.BOLD, 15));
            metrics = g.getFontMetrics();
            textWidth = metrics.stringWidth(text);
            while (textWidth <= wdth) {
                //if the text is shorter than the applet width
                //we shoul repeat it after a "+" sign.
                text += "+" + line;
                textWidth = metrics.stringWidth(text);
            text = text + "+";
            text = "++" + text;
            textWidth = metrics.stringWidth(text);
            //repainting the applet
            while (flag) {
                if (i < -textWidth) i = 0;
                i--;
                repaint();
                try {
                    Thread.sleep(delay * 20);
                } catch (InterruptedException e) {
         * Start the thread.
        public void start() {
            new Thread(this).start();
         * Stop the thread.
        public void stop() {
            flag = false;
        public void destroy() {
    }

  • Problem writing an applet

    I can't figure out how to write the if-else code to determine the outcome of the game. This is because I can't figure out how to write the value of the variable for the picked card! I've commented on the part where I am having problems.
    // User is asked to guess which of the two face down cards has
    // the greatest value. The face value is the only thing used to
    // determine the value of the cards. When the user selects a card,
    // the fronts of the cards are shown, and the result of the game is
    // displayed. The user is aksed if he or she wishes to play again.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class Exercise4 extends Applet implements MouseListener
    DeckOfCards deck;
    Card card1, card2, drawnCard1, drawnCard2;
    String result, message, programmerName = "2";
    Font bigFont;
    Image cardpics; by-60
    public void init()
    setBackground( Color.cyan );
    setSize (320,250);
    addMouseListener(this);
    cardpics = getImage(getCodeBase(), "cards.gif");
    bigFont = new Font("Serif", Font.BOLD, 14);
    deck = new DeckOfCards();
    deal();
    // Start the game by dealing two cards and repainting the applet.
    void deal()
    card1 = card2 = drawnCard1 = drawnCard2 = null;
    message = "Which Card is Higher?";
    result = "";
    deck.shuffle();
    deck.deal();
    repaint();
    // Because the applet is registered to listen for mouse clicks on
    // itself, the system will call this method when the user presses
    // the mouse on the applet. In this case, the method checks whether
    // the user clicked on one of the cards or on the message at the
    // bottom of the screen. If the user clicked card N, this method
    // calls clickedCard(N). If the user clicked on the message, this
    // method calls clickedMessage().
    public void mousePressed(MouseEvent evt)
    int x = evt.getX(); // convenient name for x-coord of mouse
    int y = evt.getY(); // convenient name for y-coord of mouse
    if ( y > 20 && y < 80 )
    if (x > 100 && x < 140)
    clickedCard(1);
    else if (x > 160 && x < 200)
    clickedCard(2);
    else
    if (x > 33 && x > 25)
    deal();
    // This method is called (by the mousePressed() method given below)
    // when the user clicks on one of the cards. The parameter, cardNum,
    // tells which card was clicked. String result is set to the appropriate
    // message telling the outcome of the game.
    void clickedCard(int cardNum)
    // I can't see to pick up the right card value and display it. I don't think I am using the method above right?
    cardNum = card1.getValue();
    if (card1.getValue() > card2.getValue())
    message = "You win!";
    else if (card1.getValue() < card2.getValue())
    message = "Too Bad - You Lose";
    else if (card1.getValue() == card2.getValue())
    message = "A Draw";
    drawnCard1 = card1;
    drawnCard2 = card2;
    message = "Play Again?";
    repaint();
    // The paint method is called by the system when the applet needs
    // to be repainted. In this applet, it draws the two cards
    // and the messages at the bottom of the applet.
    public void paint(Graphics g)
    int width = getSize().width;
    int height = getSize().height;
    FontMetrics fm = getFontMetrics(bigFont);
    int w;
    g.setColor(Color.blue);
    g.drawRect(0,0,width-1,height-1);
    g.setColor(Color.pink); background.
    g.fillRect(33, 105, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 105, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(message);
    g.drawString( message, 86, 122);
    g.setColor(Color.pink);
    g.fillRect(33, 155, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 155, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(result);
    g.drawString( result, 20, 30);
    g.setColor(Color.pink);
    g.fillRect(33, 205, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 205, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(programmerName);
    g.drawString( programmerName, 65, 222);
    drawCard( g, drawnCard1, 100, 20 ); // Draw the two cards.
    drawCard( g, drawnCard2, 160, 20 ); // If drawnCard1 or drawnCard2 are null,
    // the cards will be drawn face down.
    // Draws a card as a 40 by 60 rectangle with
    // upper left corner at (x,y). The card is drawn
    // in the graphics context g. If card is null, then
    // a face-down card is drawn.
    void drawCard(Graphics g, Card card, int x, int y)
    if (card == null)
    // Draw a face-down card
    g.setColor(Color.blue);
    g.fillRect(x,y,40,60);
    g.setColor(Color.white);
    g.drawRect(x+3,y+3,33,53);
    g.drawRect(x+4,y+4,31,51);
    else
    int row = 0;
    switch (card.getSuit())
    case 0: row = 0; break;
    case 1: row = 1; break;
    case 2: row = 2; break;
    case 3: row = 3; break;
    int sx, sy; // coords of upper left corner in the source image.
    sx = 40*(card.getValue() - 1);
    sy = 60*row;
    g.drawImage(cardpics, x, y, x+40, y+60,
    sx, sy, sx+40, sy+60, this);
    // Other mouse routines required by the MouseListener interface.
    // They are not used in this applet
    public void mouseClicked(MouseEvent evt) { }
    public void mouseReleased(MouseEvent evt) { }
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }
    // DeckOfCards.java
    import java.util.Random;
    public class DeckOfCards
    private int count;
    private boolean[] deck = new boolean[53];
    Random generator = new Random();
    public DeckOfCards()
    shuffle();
    public void shuffle()
    for (int i = 1; i <= 52; i++)
    deck = false;
    count = 0;
    public Card deal()
    int num, suit;
    if (count > 51)
    num = -1;
    suit = -1;
    else
    do
    num = generator.nextInt(13) + 1;
    suit = generator.nextInt(4);
    while (deck[num+suit*13] == true);
    deck[num+suit*13] = true;
    count++;
    return new Card(num,suit);
    public int cardsInDeck()
    return (52 - count);
    // Card.java
    public class Card
    private int num, suit;
    public Card (int num, int suit)
    this.num = num;
    this.suit = suit;
    public int getValue ()
    return num;
    public int getSuit ()
    return suit;
    public String toString()
    String result = "message";
    switch (num)
    case -1: result = " No Card"; break;
    case 1: result = " Ace "; break;
    case 2: result = " 2 "; break;
    case 3: result = " 3 "; break;
    case 4: result = " 4 "; break;
    case 5: result = " 5 "; break;
    case 6: result = " 6 "; break;
    case 7: result = " 7 "; break;
    case 8: result = " 8 "; break;
    case 9: result = " 9 "; break;
    case 10: result = " 10 "; break;
    case 11: result = " Jack "; break;
    case 12: result = " Queen"; break;
    case 13: result = " King "; break;
    switch (suit)
    case -1: break;
    case 0: result = result + " of Clubs"; break;
    case 1: result = result + " of Hearts"; break;
    case 2: result = result + " of Spades"; break;
    case 3: result = result + " of Diamonds"; break;
    return result;
    }

    Assuming it's this one than this problem is solved:
    http://forum.java.sun.com/thread.jspa?threadID=671142

  • There is anyone can convert applet code to application code?

    i got this applet code and would like to convert it to application code but don't know how.Anybody convert this please?
    thanks in advance.
    [email protected]
    //This program was completely written by Peter Wetsel.
    //If there are any questions about this code you
    //can email me at [email protected]
    //To get it to compile using jdk type "javac -nowarn battle.java".
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    import java.lang.*;
    public class battle extends java.applet.Applet implements Runnable {
         Color col;
         String message= new String("");//holds the message placed in the upper left
         String Status = new String("");
         String message2[]= new String[5];//holds the destroyed messages in order for repainting.
         int hits=0;//the total number of hits by the player
         int numDestroyed=0;//the number of ships destroyed by the player
         int battlepos[]=new int[4];//the 4 positions of the battleship
    int carrierpos[]=new int[5];//the 5 positions of the carrier
         int subpos[]=new int[3];//the 3 positions of the submarine
         int patrolpos[]=new int[2];//the 2 positions of the patrol boat
         int destroyerpos[]=new int[3]; //the 3 positions of the destroyer
         int guesses=0;// the number of guesses by the player
         int player[][]=new int[10][10]; //to hold the positions of the player.(not until version 2)
         int guessed[][]=new int[10][10]; //hold the places that have been guessed by the player
         int computer[][]=new int[10][10]; //holds where the computers ships are
         int battleshipHitCt, destroyerHitCt, subHitCt, patrolHitCt, carrierHitCt;//keeps the hit count for each of the ships
         boolean init=false;//false until play is pushed.
         boolean ok=false;//boolean that is true if current boat position chosen by random is ok(getcarrier(), etc.)
         boolean battleOK=true;//false when the type of ship is destroyed
         boolean patrolOK=true;//...
         boolean subOK=true;//...
         boolean destroyerOK=true;//...
         boolean carrierOK=true;//...
         boolean won=false;//true when the player has won
         int o;
    public static void main (String args [])
    Frame frame = new Frame () ;
    battle applet = new battle () ;
    frame.add (applet) ;
    applet.init () ;
    applet.paint(g);
    applet.start () ;
         public void getCarrier(){
              int x, y, dir; //will hold a random x & y coordinate(0-9), and a random direction(0-1)(N,E,S,W)
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              if(dir==0)
                   while(y<4){
                        y=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x][y-i]=1;
                        carrierpos=x*10+y-i;
              if (dir==1)
                   while(x>5){
                        x=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x+i][y]=1;
                        carrierpos[i]=(x+i)*10+y;
              if (dir==2)
                   while(y>5){
                        y=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x][y+i]=1;
                        carrierpos[i]=x*10+y+i;
              if (dir==3)
                   while(x<4){
                        x=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x-i][y]=1;
                        carrierpos[i]=(x-i)*10+y;
         public void getBattle(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<3){
                             y=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>6){
                             x=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>6){
                             y=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<3){
                             x=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<4; i++){
                        computer[x][y-i]=1;
                        battlepos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<4; i++){
                        computer[x+i][y]=1;
                        battlepos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<4; i++){
                        computer[x][y+i]=1;
                        battlepos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<4; i++){
                        computer[x-i][y]=1;
                        battlepos[i]=(x-i)*10+y;
         public void getSub(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<2){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>7){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>7){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<2){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<3; i++){
                        computer[x][y-i]=1;
                        subpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<3; i++){
                        computer[x+i][y]=1;
                        subpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<3; i++){
                        computer[x][y+i]=1;
                        subpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<3; i++){
                        computer[x-i][y]=1;
                        subpos[i]=(x-i)*10+y;
         public void getDestroyer(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<2){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>7){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>7){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<2){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<3; i++){
                        computer[x][y-i]=1;
                        destroyerpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<3; i++){
                        computer[x+i][y]=1;
                        destroyerpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<3; i++){
                        computer[x][y+i]=1;
                        destroyerpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<3; i++){
                        computer[x-i][y]=1;
                        destroyerpos[i]=(x-i)*10+y;
         public void getPatrol(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<1){
                             y=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>8){
                             x=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>8){
                             y=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<1){
                             x=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<2; i++){
                        computer[x][y-i]=1;
                        patrolpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<2; i++){
                        computer[x+i][y]=1;
                        patrolpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<2; i++){
                        computer[x][y+i]=1;
                        patrolpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<2; i++){
                        computer[x-i][y]=1;
                        patrolpos[i]=(x-i)*10+y;
         public void run(){// to be in here so can compile
         public void init() {
              for (int i=0; i<10; i++){//initializes the guessed matrix to be all 2's(not been guessed)
                   for (int j=0;j<10; j++){
                        guessed[i][j]=2;
              for (int i=0; i<2; i++){//initializes array to be all zeros
                   patrolpos[i]=0;
              for (int i=0; i<2; i++){
                   destroyerpos[i]=0;
              for (int i=0; i<2; i++){
                   subpos[i]=0;
              for (int i=0; i<2; i++){
                   carrierpos[i]=0;
              for (int i=0; i<2; i++){
                   battlepos[i]=0;
              battleshipHitCt=0;//initialize all hit counts
              destroyerHitCt=0;
              subHitCt=0;
              patrolHitCt=0;
              carrierHitCt=0;
         //get all boat positions
              getCarrier();
              ok=false;
              getBattle();
              ok=false;
              getDestroyer();
              ok=false;
              getSub();
              ok=false;
              getPatrol();
         public void paint(Graphics g) { //this is the shots paint method... draws a line from its last position to its current position, basically
         if (!init && !won){//draws screen before play is pushed
                   g.setColor(col.white);
                   g.fillRect(0,0,600,320);
                   g.setColor(col.black);
                   g.fillRect(20,20,30,25);
                   g.setColor(col.white);
                   g.drawString("PLAY", 23,30);
                   g.setColor(col.black);
                   g.drawString("This is different that usual battleship, here the goal is",23,65);
                   g.drawString("to find all of the computers ships in the least number of guesses.",23,85);
                   g.drawString("<30 turns --- You have too much luck!", 23, 105);
                   g.drawString("31-50 turns --- Excellent!", 23, 125);
                   g.drawString(">=51 turns --- You have no skills!", 23, 145);
                   g.drawString("PRESS PLAY TO BEGIN", 23, 165);
              if (init && !won){//draws grid and messages
                   g.setColor(col.black);
                   g.fillRect(0,0,600,320); //makes big, black rectangle washover
                   g.setColor(col.white);
                   g.drawString("# of Guesses = " + guesses,500, 280);
                   for (int i=0; i<11; i++)
                        g.drawLine(20,20+i*28, 300, 20+i*28);
                   for (int i=0; i<11; i++)
                        g.drawLine(20+i*28,20,20+i*28,300);
                   char ch='A';
                   for (int i=0; i<10; i++){//draws letter accross the top
                        g.drawString(ch+" ",30+28*i,13);
                        ch++;
                   ch='1';
                   for (int i=0; i<9; i++){//draws numbers down the side
                        g.drawString(ch+" ",10,40+28*i);
                        ch++;
                   g.drawString("10", 6,290);
                   g.drawString(message,420,40);
                   for (int i=0; i<numDestroyed; i++){
                        g.drawString(message2[i], 305, 40+(i+1)*20);
                   g.setColor(col.black);
                   //next puts in any circles already guessed
                   for (int i=0; i<10; i++)
                        for (int j=0; j<10;j++){
                             if (guessed[i][j]==1)     {
                                  g.setColor(col.red);
                                  g.fillOval(i*28+30, j*28+30, 10,10);
                             if (guessed[i][j]==0)     {
                                  g.setColor(col.white);
                                  g.fillOval(i*28+30, j*28+30, 10,10);
         public boolean seeifahit(int x, int y){//sees if the shot was a hit or not
              if(computer[x][y]==1)
                   return true;
              return false;
         public String getshiptype(int x, int y){//returns the name of the ship that was hit
              for (int i=0;i<4; i++)
                   if (battlepos[i]==x*10+y){
                        battleshipHitCt++;
                        return "Battleship";
              for (int i=0;i<3; i++)
                   if (subpos[i]==x*10+y){
                        subHitCt++;
                        return "Submarine";
              for (int i=0;i<2; i++)
                   if (patrolpos[i]==x*10+y){
                        patrolHitCt++;
                        return "Patrol Boat";
              for (int i=0;i<5; i++)
                   if (carrierpos[i]==x*10+y){
                        carrierHitCt++;
                        return "Carrier";
              for (int i=0;i<3; i++)
                   if (destroyerpos[i]==x*10+y){
                        destroyerHitCt++;
                        return "Destroyer";
              return " ";
         public void gameOver(){//displays guesses and ends
              if (!won){
                   Graphics g = getGraphics() ;
                   g.setColor(col.black);
                   g.fillRect(0,0,600,320); //makes big, black rectangle washover
                   g.setColor(col.white);
                   g.drawString("YOU WIN!!", 200,100);
                   String out=new String("It took you "+guesses+" tries!");
                   g.drawString(out, 200,120);
                   g.drawString("Press refresh on your browser to play again", 200, 150);
                   won=true;
         public boolean destroyed(){
              if(battleshipHitCt==4 && battleOK)
                   battleOK=false;
                   return true;
              if(carrierHitCt==5 && carrierOK)
                   carrierOK=false;
                   return true;
              if(subHitCt==3 && subOK)
                   subOK=false;
                   return true;
              if(patrolHitCt==2 && patrolOK)
                   patrolOK=false;
                   return true;
              if(destroyerHitCt==3 && destroyerOK)
                   destroyerOK=false;
                   return true;
              return false;
         public boolean mouseDown(Event e, int x, int y) {//handles when a mouse key is pressed(either key)
              String type= new String("");
              if (!won){
                   message="";
                   Graphics g = getGraphics() ;
                   g.setColor(col.white);
                   int xindex, yindex, val;
                   if (x>20 && y>20 && y<300 && x<300 && init){
                        guesses++;
                        g.setColor(col.black);
                        g.fillRect(490,260, 550, 285);
                        g.setColor(col.white);
                        g.drawString("# of Guesses = " + guesses,500, 280);
                        g.setColor(col.black);
                        g.fillRect(419,30,580,95);
                        g.setColor(col.white);
                        xindex=(x-20)/28;//converts x coordinate into index(A-J) in form of (0-9)
                        yindex=(y-20)/28;//converst y coordinate into index(0-9)
                        val=guessed[xindex][yindex];
                        if (val==2){
                             if (seeifahit(xindex,yindex)){
                                  type=getshiptype(xindex, yindex);
                                  hits++;
                                  g.setColor(col.white);
                                  guessed[xindex][yindex]=1;
                                  if (!destroyed()){
                                       message=type + " Hit";
                                       g.drawString(message, 420, 40);
                                  else{
                                       g.setColor(col.white);
                                       message2[numDestroyed]=new String("");
                                       message2[numDestroyed]=type + "Destroyed";
                                       numDestroyed++;
                                       g.drawString(message2[numDestroyed-1] , 305, 40+(numDestroyed)*20);
                                  g.setColor(col.red);
                             else guessed[xindex][yindex]=0;
                             g.fillOval(xindex*28+30, yindex*28+30, 10,10);
    else {
                             g.setColor(col.white);
                             message="That has already been guessed";
                             g.drawString(message,420,40);
                   if (x>20 && x<40 && y>20 && y<40 && !init){
                        init=true;
                        paint(g);
                   if (hits>=17){
                        gameOver();
                        System.exit(0);
              return true;

    replace following in main method
    applet.paint(g); by
    repaint(); and
    applet.start() by
    // applet.start() at least compile your source code and if all runs the normal way it shoul be an application
    PS: i think there is a way in javac to tell it your source is an applicat. and not an applet

  • I'm having trouble displaying an applet correctly on a consistant basis

    I have a webpage that displays two applets. I wanted only one to be visible at a time so I set one to be hidden and one to be visible. Then i made a link with a javascript function attached that would switch the visibility of the applets. The problem is when it switches visibility half of the time the applet is not displaying correctly. Buttons may be missing or the whole applet does not display. minimizing and maximizing the window makes it display correctly but I don't want to have to do this every time I switch the visibility of the applets.
    The html and javascript is shown below:
    <script language="JavaScript">
    function switchvisible()
         if(document.simple.style.visibility == 'hidden')
         document.simple.style.visibility = 'visible'
         document.question.style.visibility = 'hidden'
         document.simple['repaint']();
         document.question['repaint']();
         else
         document.simple.style.visibility = 'hidden'
         document.question.style.visibility = 'visible'
         document.simple['repaint']();
         document.question['repaint']();
    </script>
    <applet code="SimpleExample.class" height="150" width="250" hspace="1" vspace="1" id="simple" name="simple" style="visibility='hidden'">
    You do not have the correct java to display this applet</applet> CLICK HERE TO SWITCH BETWEEN VIEWING THE SIMPLE SHAPES AND THE QUESTION
    <applet code="ClickLines3.class" height=200 width=350 hspace=10 vspace=10 id="question" name="question">
    your browser does not support java </applet>
    Is there any way to get this to display correctly without minimizing and maximizing the window everytime I change the visibility?

    Also this problem only occurs in internet explorer, Mozzila displays the applets correctly so its browser related.

  • Refresh the applet !!!!!!

    We developed an internationalizated applet with jdk1.3.0 and we used hide and show functions
    to repaint the applet and obtain the applet with the new language selected.
    Now in Swing with jdk1.3.1 hide and show are deprecated and the setVisible doesn't do the same.
    We have tried some options, here you have the code of the function that realizes the change of
    the idiom:
    private void canviIdioma( String str )
    if( str.equals( "Angl?s" ) )
    language = new String( "en" );
    country = new String( "US" );
    if(str.equals( "Catal?" ))
    language = new String( "ca" );
    country = new String( "CA" );
    currentLocale = new Locale( language,country );
    missatges = ResourceBundle.getBundle( "ResourceBundle",currentLocale );
    myCollator=Collator.getInstance( currentLocale );
    repaint();
    System.out.println(missatges.getString("titol1"));
    // getContentPane().invalidate();
    // getContentPane().validate();
    // setVisible(false); //hide
    // setVisible(true); //show
    // hide();
    // show();
    // invalidate();
    // repaint();
    // revalidate();
    // getContentPane().revalidate();
    // doLayout();
    // setVisible(true);
    The change of the idiom is done correctly because the System.out.println writes the correct string.
    What must we do to repaint ?
    Thanks

    The only thing which comes to my mind now is that you are not specifying what to repaint.
    If the applet is in the same class, try
    this.repaint();
    If you the applet in a different class like
    class hello extends applet
    //code
    then you can call
    hello.repaint();

  • Multithreadded applet just will not die. Why?

    Hi!
    The applet code is below. In short, it
    has four classes:
    Mulka - a simple graphic object to draw (basically
    a cross)
    DaThing - a Thread class which draws many many
    Mulkas
    AnotherThing - a thread class which draws a
    string on top of mulkas.
    And, of course, the main applet class.
    The main applet class create two objects: one
    instance of DaThing and on instance of
    AnotherThing then starts them both. So, they
    are drawing at the same time. After that
    the applet does not do a thing. However, it
    handles mouseDown event and if the mouse
    got down 5 times the applet stops the
    threads and stops itself.
    The problem is that IT DOES stop the
    threads but continues to execute itself, so,
    clicking the mouse will still draw a box and
    repaint the applet graphics area. Why is that?
    How do i completely stop the applet?
    Regards,
    Artem
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    // graphics object to draw
    public class Mulka {
           private int x,y;
           private int hx,hy;
           private final int width=16;
           private final int height=16;
           private Color bgcolor;
           private Color color;
           public void setcolor (Color c){
                  color=c;
           public void setxy(int x, int y) {
                  this.x=x;
                  this.y=y;
           public void sethotspot(int x, int y) {
                  hx=x;
                  hy=y;
           public void setbgcolor (Color c){
                  bgcolor=c;
           public void draw(Graphics g) {
                  // a simple cross
                  g.setColor(color);
                  g.drawLine(x+hx,y+hy,x+width-1+hx,y+height-1+hy);
                  g.drawLine(x+width-1+hx,y+hy,x+hx,y+height-1+hy);
           public void undraw(Graphics g) {
                  g.setColor(bgcolor);
                  g.drawLine(x+hx,y+hy,x+width-1+hx,y+height-1+hy);
                  g.drawLine(x+width-1+hx,y+hy,x+hx,y+height-1+hy);
           public Mulka (int x, int y){
                  hx=0;
                  hy=0;
                  color=Color.black;
                  bgcolor=Color.white;
                  this.x=x;
                  this.y=y;
           public Mulka (){
                  hx=0;
                  hy=0;
                  color=Color.black;
                  bgcolor=Color.white;
                  this.x=0;
                  this.y=0;
    public class AnotherThing extends Thread {
           Graphics g = null;
           String text;
           AnotherThing (String name){
                        super(name);
                        text=name;
           public void setg (Graphics g){
                  this.g=g;
           public void run (){
                  Random rand = new Random();
                  while (true){
                        try{
                            g.setColor(                                      new Color(
                                               (int)(rand.nextFloat()*255),
                                               (int)(rand.nextFloat()*255),
                                               (int)(rand.nextFloat()*255)
                            g.drawString(text,50+(int)(rand.nextFloat()*5),50);
                        catch(InterruptedException e) {
                          this.stop();
    public class DaThing extends Thread {
           Graphics g = null;
           Mulka mulkas[] = new Mulka[10];
           String text;
           DaThing (String name){
                        super(name);
                        text=name;
           public void setg (Graphics g){
                  this.g=g;
           public void run (){
                  int i;
                  Random rand=new Random();
                  while(true){
                              try{
                                for (i=0;i<10;i++){
                                    mulkas=new Mulka();
    mulkas[i].setxy(
    (int)(rand.nextFloat()*300),
    (int)(rand.nextFloat()*200));
    mulkas[i].setcolor(
    new Color(
    (int)(rand.nextFloat()*255),
    (int)(rand.nextFloat()*255),
    (int)(rand.nextFloat()*255)
    for (i=0;i<10;i++){
    mulkas[i].draw(g);
    catch(InterruptedException e) {
    this.stop();
    public class OffScreen extends Applet {
    DaThing draw_thread = null;
    AnotherThing thing= null;
    int waitforclicks=5;
    public void init () {
    System.out.println("Applet inited");
    waitforclicks=5;
    resize(320,240);
    public void start() {
    System.out.println("Applet started");
    if (draw_thread == null){
    draw_thread = new DaThing("First thread");
    draw_thread.setg(getGraphics());
    draw_thread.start();
    if (thing == null){
    thing = new AnotherThing("Another thread");
    thing.setg(getGraphics());
    thing.start();
    public void stop() {
    if (draw_thread != null){
    draw_thread.stop();
    draw_thread=null;
    if (thing != null){
    thing.stop();
    thing=null;
    System.out.println("Applet finished");
    public boolean mouseDown(Event evt, int x, int y){
    Graphics g=getGraphics();
    System.out.println("Clicked mouse");
    g.fillRect(x,y,50,50);
    repaint();
    waitforclicks--;
    if (waitforclicks<1){
    System.out.println("This was the last click");
    stop();
    return true;

    Thanks for replies.
    As for exit then I think is should be done like
    Runtime rt=getRuntime();
    rt.exit(0);But it works only in debugger :( In a browser exit()
    is just ignored.
    So, basically, the only way to at least emulate
    visually the death of an applet i should do something
    like below (notice the isActive flag). Is it so?
    import java.applet.*;
    import java.awt.*;
    import java.lang.*;
    public class DieTest extends Applet {
           int count=5;
           int x=0;
           boolean isActive=true;
           public void init() {
                  System.out.println("Applet inited");
           public void stop() {
                  System.out.println("Applet Stopped");
           public boolean mouseDown(Event evt, int x, int y){
                  Runtime a = Runtime.getRuntime();
                  Graphics g=getGraphics();
                  if (isActive==true){
                     count--;
                     System.out.println("Clicked mouse: "+x);
                     g.drawString(count+"",x,y);
                     if (count<1){
                        System.out.println("Clicked last time");
                        stop();
                        isActive=false;
                  return true;
    }

  • Applet abends!!!

    I am completely new to applets! There are absolutely no errors shown, but the game abends every time I try to determine whether or not the user wins or loses. This is the main mehtod and the two constructors:
    // User is asked to guess which of the two face down cards has
    // the greatest value. The face value is the only thing used to
    // determine the value of the cards. When the user selects a card,
    // the fronts of the cards are shown, and the result of the game is
    // displayed. The user is aksed if he or she wishes to play again.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class Exercise4 extends Applet implements MouseListener
    DeckOfCards deck;
    Card card1, card2, drawnCard1, drawnCard2;
    String result, message, programmerName = "2";
    Font bigFont;
    Image cardpics; by-60
    public void init()
    setBackground( Color.cyan );
    setSize (320,250);
    addMouseListener(this);
    cardpics = getImage(getCodeBase(), "cards.gif");
    bigFont = new Font("Serif", Font.BOLD, 14);
    deck = new DeckOfCards();
    deal();
    // Start the game by dealing two cards and repainting the applet.
    void deal()
    card1 = card2 = drawnCard1 = drawnCard2 = null;
    message = "Which Card is Higher?";
    result = "";
    deck.shuffle();
    deck.deal();
    repaint();
    // Because the applet is registered to listen for mouse clicks on
    // itself, the system will call this method when the user presses
    // the mouse on the applet. In this case, the method checks whether
    // the user clicked on one of the cards or on the message at the
    // bottom of the screen. If the user clicked card N, this method
    // calls clickedCard(N). If the user clicked on the message, this
    // method calls clickedMessage().
    public void mousePressed(MouseEvent evt)
    int x = evt.getX(); // convenient name for x-coord of mouse
    int y = evt.getY(); // convenient name for y-coord of mouse
    if ( y > 20 && y < 80 )
    if (x > 100 && x < 140)
    clickedCard(1);
    else if (x > 160 && x < 200)
    clickedCard(2);
    else
    if (x > 33 && x > 25)
    deal();
    // This method is called (by the mousePressed() method given below)
    // when the user clicks on one of the cards. The parameter, cardNum,
    // tells which card was clicked. String result is set to the appropriate
    // message telling the outcome of the game.
    void clickedCard(int cardNum)
         cardNum = card1.getValue();
         if (card1.getValue() > card2.getValue())
         message = "You win!";
         else if (card1.getValue() < card2.getValue())
                   message = "Too Bad - You Lose";
         else if (card1.getValue() == card2.getValue())
              message = "A Draw";
         drawnCard1 = card1;
         drawnCard2 = card2;
    message = "Play Again?";
    repaint();
    // The paint method is called by the system when the applet needs
    // to be repainted. In this applet, it draws the two cards
    // and the messages at the bottom of the applet.
    public void paint(Graphics g)
    int width = getSize().width;
    int height = getSize().height;
    FontMetrics fm = getFontMetrics(bigFont);
    int w;
    g.setColor(Color.blue);
    g.drawRect(0,0,width-1,height-1);
    g.setColor(Color.pink); background.
    g.fillRect(33, 105, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 105, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(message);
    g.drawString( message, 86, 122);
    g.setColor(Color.pink);
    g.fillRect(33, 155, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 155, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(result);
    g.drawString( result, 20, 30);
    g.setColor(Color.pink);
    g.fillRect(33, 205, 250, 25);
    g.setColor(Color.blue);
    g.drawRect(33, 205, 250, 25);
    g.setFont( bigFont );
    w = fm.stringWidth(programmerName);
    g.drawString( programmerName, 65, 222);
    drawCard( g, drawnCard1, 100, 20 ); // Draw the two cards.
    drawCard( g, drawnCard2, 160, 20 ); // If drawnCard1 or drawnCard2 are null,
    // the cards will be drawn face down.
    // Draws a card as a 40 by 60 rectangle with
    // upper left corner at (x,y). The card is drawn
    // in the graphics context g. If card is null, then
    // a face-down card is drawn.
    void drawCard(Graphics g, Card card, int x, int y)
    if (card == null)
    // Draw a face-down card
    g.setColor(Color.blue);
    g.fillRect(x,y,40,60);
    g.setColor(Color.white);
    g.drawRect(x+3,y+3,33,53);
    g.drawRect(x+4,y+4,31,51);
    else
    int row = 0;
    switch (card.getSuit())
    case 0: row = 0; break;
    case 1: row = 1; break;
    case 2: row = 2; break;
    case 3: row = 3; break;
    int sx, sy; // coords of upper left corner in the source image.
    sx = 40*(card.getValue() - 1);
    sy = 60*row;
    g.drawImage(cardpics, x, y, x+40, y+60,
    sx, sy, sx+40, sy+60, this);
    // Other mouse routines required by the MouseListener interface.
    // They are not used in this applet
    public void mouseClicked(MouseEvent evt) { }
    public void mouseReleased(MouseEvent evt) { }
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }
    // DeckOfCards.java
    import java.util.Random;
    public class DeckOfCards
    private int count;
    private boolean[] deck = new boolean[53];
    Random generator = new Random();
    public DeckOfCards()
    shuffle();
    public void shuffle()
    for (int i = 1; i <= 52; i++)
    deck[i] = false;
    count = 0;
    public Card deal()
    int num, suit;
    if (count > 51)
    num = -1;
    suit = -1;
    else
    do
    num = generator.nextInt(13) + 1;
    suit = generator.nextInt(4);
    while (deck[num+suit*13] == true);
    deck[num+suit*13] = true;
    count++;
    return new Card(num,suit);
    public int cardsInDeck()
    return (52 - count);
    // Card.java
    public class Card
    private int num, suit;
    public Card (int num, int suit)
    this.num = num;
    this.suit = suit;
    public int getValue ()
    return num;
    public int getSuit ()
    return suit;
    public String toString()
    String result = "message";
    switch (num)
    case -1: result = " No Card"; break;
    case 1: result = " Ace "; break;
    case 2: result = " 2 "; break;
    case 3: result = " 3 "; break;
    case 4: result = " 4 "; break;
    case 5: result = " 5 "; break;
    case 6: result = " 6 "; break;
    case 7: result = " 7 "; break;
    case 8: result = " 8 "; break;
    case 9: result = " 9 "; break;
    case 10: result = " 10 "; break;
    case 11: result = " Jack "; break;
    case 12: result = " Queen"; break;
    case 13: result = " King "; break;
    switch (suit)
    case -1: break;
    case 0: result = result + " of Clubs"; break;
    case 1: result = result + " of Hearts"; break;
    case 2: result = result + " of Spades"; break;
    case 3: result = result + " of Diamonds"; break;
    return result;
    }

    "Abends"? What does that mean?
    Anyway, try writing a smallest possible applet that exhibits the behavior you're seeing. That'll be easier to debug. If you can't debug it yourself, then ask again here. Ask about the smallest possible applet, though; you'll tend to scare people away with long programs posted here. When you post code, always wrap it in [code][/code] tags so it's legible; ugly unformatted code will also scare people away.

Maybe you are looking for

  • My itunes account is locked , what should i do?

    i was trying to purches chips for zynga poker and they asked me about the security questions i answered before and i couldnt remember the answeres and my account got locked , what should i do?

  • Captivate 5: Where is the history of Caption types stored?

    Hi, I recently created two image files that were meant to substitute the Text only captions for the Success/Failure outcomes for each question answered within a True/False quiz. However, for subsequent T/F qustions I cannot replace these image files

  • How upload image in my table???

    hi, i create table with a column of type blob. Now, i don`t know how put a image in this column :S. ah! for this purpose i use htmld. how upload a image in my table using htmldb. thanks P.D. Help Me :D

  • 1.1.2 Available Friday or before

    Hi all, Apologies if this is old news! The UK release of iPhone ships with 1.1.2...although apparently nothing much has been updated. Oh except that it will supposedly brick all hacked iPhones. I guess this will mean the update will be available befo

  • I need a class!

    So after reading many posts, I've come to the realization that I need a class in Imovie, Final Cut and exporting to DVD's! There are so many options, so many settings, so many "technical" terms being thrown around, how is a person supposed to know wh