Hot questions for Using Applets in string

Question:

I wrote a Java applet code using Key Event handling to demonstrate Non buffered input in Java. My code is working fine and the output is alright but I'm having trouble accomplishing another objective in this program: in the overriden keyPressed() method, I write the line: showStatus(s); , where s is the global static StringBuffer object which the characters typed from the keyboard are appended to. But the showStatus() method displays text on the status bar of the applet viewer. Therefore, the present program is usable only in an applet viewer and not in a web browser. I tried putting the statement g.drawString(String.valueOf(s),10,90); (g=Graphics class object as argument of paint()) in the paint() method to display the text in the canvas. I expected this to work as s is global and static but it's not showing any output. I used the drawString() method in paint() both with and without overriding the boolean action() method but I still didn't get anything. I just want help in displaying the typed text in the canvas of the applet.

Below is my code. Please view it for reference and to help me out the best way possible. Thank you.

/* An applet that implements the concept of non buffered user input
using Event handling method.
*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class NonBufferInput extends Applet implements KeyListener {
    public static StringBuffer s;

    @Override
    public void init() {
        addKeyListener(this);
        s=new StringBuffer();
    }//init

    @Override
    public void keyTyped(KeyEvent K) {}

    @Override
    public void keyPressed(KeyEvent K) {
       char c=K.getKeyChar();
       int i=K.getKeyCode();
       if(i==32)  //space bar
           s.append(' ');
       else if(i==10||i==16||i==20||i==32||i==17||i==524||i==18||i==525||i==27
             ||(i>=112&&i<=123)||i==145||i==19||i==155||i==36||i==33||i==127
             ||i==35||i==34||i==144||(i>=37&&i<=40));  //characters I don't want as input
       else if(i==8) {  //backspace
           if(s.length()!=1)
               s.setLength(s.length()-1);
       }
       else
           s.append(c);
       showStatus("Typed : "+s);
    }

    @Override
    public void keyReleased(KeyEvent K) {}

    @Override
    public void paint(Graphics g) {
        g.drawString("Text will be displayed on status bar as you type.",10,50);
        g.setColor(Color.blue);
        g.drawString(String.valueOf(s),10,80); //PROBLEM
    }//paint

    @Override
    public boolean action(Event event, Object obj) {
        repaint();
        return true;
    }//action
}//class

Answer:

addKeyListener(this);

Should best be:

setFocusable(true); // Sets the focusable state of this Component to the specified value.
addKeyListener(this);

Then add:

@Override
public void start() {
    requestFocusInWindow(); // Requests that this Component get the input focus ..
}//start

Question:

New in Java and might be repeated question.

Using full screen applet without title bar to render images on ever 10 millisecond time interval with help of paint method. At the same time I want specific text to be displayed on applet screen at any position.

Since images are dynamic hence I am rendering on 10 millisecond but text is fix and not going to change in whole life of applet.

Now concern is, if I draw text in paint method then its burden on paint method to draw image and text on every 10 millisecond time.

public void paint(Graphics  g) 
{   
    if(img != null)
    {
        g.drawImage(img, 0, 0, null);   
        g.drawString("Hey there!", 0, 0); //Additional load
    }           
}   

Cannot place text on title bar too.

Is it possible to draw text at once and rendered images frequently?


Answer:

public void paint(Graphics  g) 
{ 

Should instead be:

public void paint(Graphics  g) 
{ 
     super.paint(g); // paint the background, borders etc.

So given doing that will erase the previously drawn text, the answer to your question is - no.

BTW - look up 'premature optimization'.

Question:

My applet code compiles fine, however, I receive the "Applet Started" message every time. Please do not dissuade me from using AWT or Applets. I am simply trying to complete my assignment. Currently, my code is:

main method

import java.awt.*;
import java.awt.event.*;


public class Lab33ast
{

public static void main(String[] args)
    {
        Frame frame = new Frame("Lab33ast");
        frame.add(new GfxApp());
        frame.setSize(100, 750);
        frame.addWindowListener(new WindowAdapter()  {public void
        windowClosing(WindowEvent e) {System.exit(0);}});
        frame.setVisible(true);
    }
}

Continued, I have a paint method in a separate file. GfxApp

import java.awt.*;

public class GfxApp extends Panel
{

    private int td = 200;       //Time Delay on graphics

    public void paint(Graphics g)
    {

        g.setFont(new Font("Arial", Font.BOLD, 28));
        g.drawString("Lab 33A 80/100 POINT VERSUIN", 300, 50);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString("DRAWING A LINKED LIST AS A STACK", 50, 215);
        g.drawString("DRAWING A LINKED LIST AS A QUEUE", 50, 415);
        drawStack(g);
        drawQueue(g);

    }


    public void drawStack(Graphics g) 
    {
        g.setFont(new Font("ARIAL", Font.BOLD, 20));
    }


    public void drawQueue(Graphics g)
    {
        g.setFont(new Font("ARIAL", Font.BOLD, 20));
    }
}

Next I have a file called GfxNode that our teacher told us to add without further instruction.

    import java.awt.*;


    public class GfxNode
    {
        private int x;                  // x coordinate of node
        private int y;                  // y coordinate of node
        private final int width;        // width of the gfx node
        private final int height;       // heigth of the gfx node
        private final int time;         // delay time between displays


    // GfxNode constructor instantiates an object and
    // stores its Top-Left coordinate (tlx,tly) information, as
    // well as the length and width of the node object.  A node object
    // with two fields is drawn at the specified coordinate.
        public GfxNode(Graphics g, int tlx, int tly, char ltr, int clr, int dt) 
        {
            x = tlx;
            y = tly;
            width = 30;
            height = 15;
            time = dt;
            drawNode(g,clr);
            drawPointer(g,ltr,1,clr);
        }


    // Method drawNode is a private helper method to draw linked list nodes.
    // This method draws a node with two fields at a location of the
    // Top-Left coordinate information in the current object.
    private void drawNode(Graphics g, int clr)
    {
        g.setColor(getColor(clr));
        g.drawRect(x,y,width,height);
        g.drawLine(x+height,y,x+height,y+height);
        delay(time);
    }


    // Method getColor a private helper method to make it easier to use colors
    // in a graphics program.   
    private Color getColor(int clr)
    {
        Color temp = Color.white;
        switch (clr)
        {
            case 0:  temp = Color.black;    break;
            case 1:  temp = Color.red;      break;
            case 2:  temp = Color.green;    break;
            case 3:  temp = Color.blue;     break;
            case 4:  temp = Color.orange;   break;
            case 5:  temp = Color.cyan;     break;
            case 6:  temp = Color.magenta;  break;
            case 7:  temp = Color.yellow;   break;
            case 8:  temp = Color.pink;     break;
            case 9:  temp = Color.white;    break;
        }
        return temp;
    }


    // Method getX returns the top-left X-coordinate of a linked list node.
    public int getx()
    { 
        return x; 
    }


// Method getY returns the top-left Y-coordinate of a linked list node.
public int gety()
{
    return y;
}


// Method drawPointer draws a vertical pointer down to an existing node.
// The first pointer to a node uses OffSet value 1 and the second
// pointer to the same node uses OffSet value 2.  The result is that
// the second pointer is moved farther to the right.
public void drawPointer(Graphics g, char ltr, int offSet, int clr) 
{
    if (offSet == 1)
        offSet = 8;
    else
        offSet = 18;
    int x1 = x + offSet;
    int y1 = y - 20;
    int x2 = x1;
    int y2 = y - 2;
    g.setColor(getColor(clr));
    g.drawLine(x1,y1,x2,y2);
    g.drawLine(x2,y2,x2-3,y2-3);
    g.drawLine(x2,y2,x2+3,y2-3);
    drawLetter(g,ltr,x+offSet-4,y-32);
    delay(time);
}


// Method enterData draws a letter in the Data field of the GfxNode.
public void enterData(Graphics g, char ltr, int clr) 
{
    g.setColor(getColor(clr));
    drawLetter(g,ltr,x+3,y+3);  
    delay(time);
}


// Method drawLink draws a link from the current sourceNode to the
// endNode in the specified color (clr).    
public void drawLink(Graphics g, GfxNode endNode, int clr) 
{
    int x1,x2;
    int y1 = this.gety()  + height/2;
    int y2 = endNode.gety() + height/2;
    g.setColor(getColor(clr));
    if (this.getx() < endNode.getx())
    {
        x1 = this.getx() + 22;
        x2 = endNode.getx() - 2;
        g.drawLine(x1,y1,x2,y2);
        g.drawLine(x2,y2,x2-3,y2-3);
        g.drawLine(x2,y2,x2-3,y2+3);
    }
    else
    {
        x1 = endNode.getx() + 8;
        x2 = this.getx() + width + 2;
        g.drawLine(x1,y1,x2,y2);
        g.drawLine(x1,y1,x1-3,y1-3);
        g.drawLine(x1,y1,x1-3,y1+3);
    }
    delay(time);
}


// Method drawNull draws a diagonal g.drawLine in the Next
// field of a list node, to indicate a NULL value.
public void drawNull(Graphics g, int clr)
{
    g.setColor(getColor(clr));
    g.drawLine(x+height+1,y+1,x+width-1,y+height-1);
    delay(time);
}


//  Method drawLetter upper-case Letter characters.  The characters
//  are drawn in a 9x9 pixel box.
//  The (x,y) parameters indicate the coordinate of the top-left corner
//  of the box.  Only capital letters and numbers are drawn.
public void drawLetter(Graphics g, char ltr, int x, int y) 
{
    switch (ltr)
    {
        case 'A' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+4,x+8,y+4);
            break;
        case 'B' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+5,y);
            g.drawLine(x,y+8,x+5,y+8);
            g.drawLine(x,y+4,x+5,y+4);
            g.drawLine(x+5,y,x+8,y+2);
            g.drawLine(x+5,y+8,x+8,y+6);
            g.drawLine(x+5,y+4,x+8,y+2);
            g.drawLine(x+5,y+4,x+8,y+6);
            break;
        case 'C' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            break;
        case 'D' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+4,y);
            g.drawLine(x,y+8,x+4,y+8);
            g.drawLine(x+4,y,x+8,y+4);
            g.drawLine(x+4,y+8,x+8,y+4);
            break;
        case 'E' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x,y+4,x+6,y+4);
            break;
        case 'F' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+4,x+6,y+4);
            break;
        case 'G' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+6,y);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x+8,y+8,x+8,y+4);
            g.drawLine(x+8,y+4,x+4,y+4);
            break;
        case 'H' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y+4,x+8,y+4);
            break;
        case 'I' :
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x+4,y,x+4,y+8);
            break;
        case 'J' :
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x,y+8,x,y+4);
            break;
        case 'K' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+1,y+4);
            g.drawLine(x+8,y+8,x+1,y+4);
            break;
        case 'L' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y+8,x+8,y+8);
            break;
        case 'M' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y,x+5,y+5);
            g.drawLine(x+8,y+1,x+4,y+4+1);
            break;
        case 'N' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y,x+9-1,y+8);
            break;
        case 'O' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            break;
        case 'P' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+4,x+8,y+4);
            g.drawLine(x+8,y,x+8,y+4);
            break;
        case 'Q' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x+3,y+5,x+8,y+10);
            break;
        case 'R' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+4,x+8,y+4);
            g.drawLine(x+8,y,x+8,y+4);
            g.drawLine(x,y+4,x+9,y+8);
            break;
        case 'S' :
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+4,x+8,y+4);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x,y,x,y+4);
            g.drawLine(x+8,y+4,x+8,y+8);
            break;
        case 'T' :
            g.drawLine(x,y,x+8,y);
            g.drawLine(x+4,y,x+4,y+8);
            break;
        case 'U' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+8);
            g.drawLine(x,y+8,x+8,y+8);
            break;
        case 'V' :
            g.drawLine(x,y,x+4,y+8);
            g.drawLine(x+8,y,x+4,y+8);
            break;
        case 'W' :
            g.drawLine(x,y,x,y+8);
            g.drawLine(x+8,y,x+8,y+9-1);
            g.drawLine(x,y+8,x+4,y+4);
            g.drawLine(x+8,y+8,x+4,y+4);
            break;
        case 'x' :
            g.drawLine(x,y,x+9,y+8);
            g.drawLine(x,y+8,x+8,y);
            break;
        case 'y' :
            g.drawLine(x,y,x+5-1,y+4);
            g.drawLine(x+8,y,x+4,y+4);
            g.drawLine(x+4,y+4,x+4,y+8);
            break;
        case 'Z' :
            g.drawLine(x,y,x+8,y);
            g.drawLine(x,y+8,x+8,y+8);
            g.drawLine(x+8,y,x,y+8);
            break;
        default :
            g.fillRect(x,y,8,8);
    }

}


    // Method delay allows viewing the sequence in which the linked lists are drawn/
    private void delay(double n)
    {
        for (double k = 1; k < n; k+=0.00001);
    }


}

I have no idea what the above code is about or its relation to my objective. Feel free to explain it to me.

I have created another class called GfxApplet and pointed to .htm code to it.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class GfxApplet extends Applet
{

    @Override
    public void init()
    {
        super.init();
        GfxApp app = new GfxApp();
        add(app);
    }

}

My html

<html>
    <head>
    </head>
    <body bgcolor="000000">
        <center>
            <applet
                code    = "Lab33ast.class"
                width   = "500"
                height  = "300"
                >
            </applet>
        </center>
    </body>
</html>

If anyone can give specific and detailed solutions, I would much appreciate it.


Answer:

There's no Applet in your code (nothing extends from Applet).

Generally speaking you should start with a different container class, maybe Panel (since you're living in the dark ages with AWT), put all your logic into this class.

Then, when you need it, create an instance of Frame or make a class which extends from Applet and add an instance of your panel to it.

Unless you have a major driving cause to, I'd avoid using AWT directly in this way and would use Swing, Swing superseded AWT 16+ years ago, so you're likely to get better community support. See Creating a GUI With JFC/Swing for more details

Since applets are been actively blocked by most browsers now days, I'd also question their use here

Missed the "Please do not dissuade me from using AWT or Applets" disclaimer

I see the logic in extending an applet. I just have no idea where to where to put that "extends Applet" part. As I change what is extended from GfxApp, I receive numerous errors in my main method, most commonly at "gfx.addWindowListener(new WindowAdapter()". My IDE says that it cannot find symbol

Move your core logic to a Panel based class

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Panel;

public class GfxApp extends Panel {

    private int td = 200;       //Time Delay on graphics

    public void paint(Graphics g) {

        g.setFont(new Font("Arial", Font.BOLD, 28));
        g.drawString("Lab 33A 80/100 POINT VERSUIN", 300, 50);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString("DRAWING A LINKED LIST AS A STACK", 50, 215);
        g.drawString("DRAWING A LINKED LIST AS A QUEUE", 50, 415);
        drawStack(g);
        drawQueue(g);

    }

    public void drawStack(Graphics g) {
        g.setFont(new Font("ARIAL", Font.BOLD, 20));
    }

    public void drawQueue(Graphics g) {
        g.setFont(new Font("ARIAL", Font.BOLD, 20));
    }
}

Create a class which extends from Applet, add an instance of GfxApplet to it...

import java.applet.Applet;

public class GfxApplet extends Applet {

    @Override
    public void init() {
        super.init();
        GfxApp app = new GfxApp();
        add(app);
    }

}

Change your applet html code to point to it...

<html>
    <head>
    </head>
    <body bgcolor="000000">
        <center>
            <applet
                code    = "GfxApplet.class"
                width   = "500"
                height  = "300"
                >
            </applet>
        </center>
    </body>
</html>

And if you need it, you can add GfxApp to an instance of Frame when you need to...

public static void main(String[] args) {
    Frame frame = new Frame("Lab33ast");
    frame.add(new GfxApp());
    frame.setSize(100, 750);
    frame.addWindowListener(new WindowAdapter() {
        public void
                windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    frame.setVisible(true);
}

This is the basic of good management of your UI code

Question:

I was writing an simple applet program that takes an input from the user and displays them. `

public void init(){
    text1=new TextField(8);

    add(text1);

    text1.setText("0");

}
public void paint(Graphics g){
    int x=0;
    String s1,str = null;
    g.drawString("input in the  box",10,50);
    try{
        s1=text1.getText();
        str=String.valueOf(s1);


    }
    catch(Exception e){}
    g.drawString(str,75,75);
}
public boolean action (Event event,Object object){
    repaint();
    return true;
}

` in the paint() method why is that str variable must be declared to null while declaring the other string variable s1 without initialization is okay? IT doesn't compile without initialization the str variable.


Answer:

Because you only use the value of s1 in a place where it's guaranteed to have a value, but you use str in a place (the catch handler) where it isn't guaranteed to have a value if you don't initialize it to something up front, since after all, an exception could be thrown in the try prior to assigning to str.

If you moved the call to g.drawString(str,75,75); into the try, you wouldn't need the = null initializer.


Side note: s1 is already a string, so there's no need to do str = String.valueOf(s1). Just use s1 in the g.drawString(str,75,75); line.

Question:

On the for loop I have the Java applet is showing me that I have an error. I am trying to use the for loop to count the repetition of letter.

String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the 
//"letterCounts" should be a int and not a string, but I need it to be a string
     String n = letterCounts[i];
     if (n.equals("0")) {
          countString = countString + "   ";
     } else if (n.length() == 1) {
          countString = countString + " " + n + " ";
     } else {
          countString = countString + n + " ";
     }
} 
this.countLabel.setText(countString);

Answer:

You donot show the definition of letterCounts, but I bet it is int[] letterCounts.

So since letterCounts is an array of int, you cannot just assign it to a String.

Just change String n to int n and your comparison to n == 0 and it should work. See below:

    String countString = "";

    for (int i = 0; i < 26; i++)
    {
      int n = letterCounts[i];

      if (n == 0) {
        countString = countString + "   ";
      } else if (n < 10) {
        countString = countString + " " + n + " ";
      } else {
        countString = countString + n + " ";
      }
    } 

    this.countLabel.setText(countString);

Question:

So I'm trying to get a java applet to accept a set of multiple passwords, so naturally I thought to put them in array. However, only one of the passwords in the array is working, the last one in the set. None of the ones before it will work and my applet denies the others. This is my code so far:

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

public class JPasswordC extends JApplet implements ActionListener
{
private final String[] password = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};

private Container con = getContentPane();
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField passwordField = new JTextField(16);

private JLabel grantedPrompt = new JLabel("<html><font color=\"green\">Access Granted</font></html>");
private JLabel deniedPrompt = new JLabel("<html><font color=\"red\">Access Denied</font></html>");

public void init()
{
    con.setLayout(new FlowLayout());

    con.add(passwordLabel);
    con.add(passwordField);
    con.add(grantedPrompt);
    grantedPrompt.setVisible(false);
    con.add(deniedPrompt);
    deniedPrompt.setVisible(false);

    passwordField.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)
{
    String input = passwordField.getText();

    for(String p : password)
    {

        if(input.equalsIgnoreCase(p))
        {
            grantedPrompt.setVisible(true);
            deniedPrompt.setVisible(false);
        }
        else
        {
            grantedPrompt.setVisible(false);
            deniedPrompt.setVisible(true);
        }
    }
}
}

How would I get this to work properly? Am I doing something wrong with the array? Is it something in the code altogether?


Answer:

The code is checking each password even if a valid one is found meaning that even if a valid password is found it will still change based on the validity of the next password. So the last one in the array declares the status of grantedPrompt and deniedPrompt. Try adding a break after the input is equal to one of the passwords.

for(String p : password)
{

    if(input.equalsIgnoreCase(p))
    {
        grantedPrompt.setVisible(true);
        deniedPrompt.setVisible(false);
        break; // break out or loop once found
    }
    else
    {
        grantedPrompt.setVisible(false);
        deniedPrompt.setVisible(true);
    }
}

Question:

I am trying to make a game where you have to guess a number, i decided to add easter eggs to the game, but whenever i try to check for the easter egg it only works with the last one

public class Guess extends Applet implements ActionListener
{
    util u = new util(); //Utility class
    int answer = u.rand(1,100); //Randomize answer
    String ansWord = Integer.toString(answer); //Convert Integer to String
    int winloss = 1; //Set winloss to display startup message
    TextField input; //Declare TextField
    boolean pizza,blazeIt; //Easter Eggs
    String response; //Declare Strings
    public void init()
    {
        input = new TextField(5);
        add(input);
        input.addActionListener(this);
    }

    public void paint(Graphics g)
    {
        g.drawString(""+winloss,10,20);
        switch(winloss)
        {
            case 1:g.drawString("Guess What Number I Am Thinking Of",getWidth()/2-100,50);
            break;
            case 2:g.drawString("How did you know?!?!?!",getWidth()/2-50,50);
            break;
            case 3:g.drawString("Nope",getWidth()/2-5,50);
            break;
            case 4:pizza = true;
            break;
            case 5:blazeIt = true;
            break;
            default:g.drawString("Broken",10,10);
            break;
        }
        easterCheck(g);
    }

    public void actionPerformed(ActionEvent e)
    {
        response = String.valueOf(input.getText());
        if(response.equals(ansWord))
        {
            winloss = 2;
        }

        else
        {
            easter("420",5); //Does not work
            easter("Pizza",4); //Works
        }
        repaint();
    }

    public void easter(String wordInput, int output)
    {
        if(response.equals(wordInput))
        {
            winloss = output;
        }
        else
        {
            winloss = 3;
        }
    }

    public void easterCheck(Graphics g)
    {
        if(pizza)
        {
            g.drawString("Delicious!",10,getHeight()-10);
        }
        if(blazeIt)
        {
            g.drawString("Blaze it!",10,getHeight()-20);
        }
    }

}

How do i fix this?


Answer:

Because everytime after you call easter("420",5), you will always call easter("Pizza",4) in the next. So if the input is "420", you know it's scecial string and you set winloss=4. But after that, inside easter("Pizza",4), you compare your input (which is "420") to "Pizza", and you reset winloss=3. That's how your code doesn't work.

public class Guess extends Applet implements ActionListener
{
  util u = new util(); //Utility class
  int answer = u.rand(1,100); //Randomize answer
  String ansWord = Integer.toString(answer); //Convert Integer to String
  int winloss = 1; //Set winloss to display startup message
  TextField input; //Declare TextField
  boolean pizza,blazeIt; //Easter Eggs
  String response; //Declare Strings
  public void init()
  {
    input = new TextField(5);
    add(input);
    input.addActionListener(this);
  }

  public void paint(Graphics g)
  {
    g.drawString(""+winloss,10,20);
    switch(winloss)
    {
      case 1:g.drawString("Guess What Number I Am Thinking Of",getWidth()/2-100,50);
        break;
      case 2:g.drawString("How did you know?!?!?!",getWidth()/2-50,50);
        break;
      case 3:g.drawString("Nope",getWidth()/2-5,50);
        break;
      case 4:pizza = true;
        break;
      case 5:blazeIt = true;
        break;
      default:g.drawString("Broken",10,10);
        break;
    }
    easterCheck(g);
  }

  public void actionPerformed(ActionEvent e)
  {
    response = String.valueOf(input.getText());
    if(response.equals(ansWord))
    {
      winloss = 2;
    } else if (response.equals("420")) {
      winloss = 5;
    } else if (response.equals("Pizza")) {
      winloss = 4;
    } else {
      winloss = 3;
    }
    repaint();
  }

  public void easterCheck(Graphics g)
  {
    if(pizza)
    {
      g.drawString("Delicious!",10,getHeight()-10);
    }
    if(blazeIt)
    {
      g.drawString("Blaze it!",10,getHeight()-20);
    }
  }

}

Question:

I want to display a double variable on the screen, using the paint () in AWT applets. I tried using

g.drawString (double, 1, 700, 400, 300);

This gives me an error. Any help. Is there any other way to put variables on the screen.


Answer:

Graphics#drawString only accepts a String value (there is also a varient that accepts AttributedCharacterIterator, but I'm pretty sure that's not what you're trying to use). Also, Graphics#drawString only takes three parameters, a String or AttributedCharacterIterator and two int values...

You could use Double.toString or NumberFormat to convert the value to a String, depending on what you are trying to achieve

g.drawString(NumberFormat.getNumberInstance().format(doubleValue), 100, 100);

You may also want to take a look at FontMetrics to better calculate the position of the text