Can anyone look at this code and tell me what I did wrong this time? This isn't behaving as I had thought it would - I wanted one character (a "p"" in this case) to be printed in a different color. I know there's a lot inelegant about this program - it just seemed like a nice example to start from. I figure I can make it pretty later!
I know the problem I'm having is somewhere in the paint() method - it's like that "if" statement isn't getting executed at all. Why not?
And the reason for that "APPLET" code at the top is a tip from a Java text, since I have to use the appletviewer to test applets (sysadmin won't load the Java plug-in for this browser until it's absolutely needed).
Here's the code:
/*
<APPLET CODE="assignment2.class" WIDTH=300 HEIGHT=300></APPLET>
*/
import java.util.*;
import java.applet.Applet;
import java.awt.*; // import the java.awt package
import java.lang.String;
import java.awt.event.*; // import the java.awt.event package
publicclass assignment2 extends Applet implements ActionListener,
MouseListener
{
Font f;
String namearray = " ", command = " ";
TextField input;
int xcord, ycord;
int index;
publicvoid init()
{
setBackground(Color.blue);
setForeground(Color.black);
input = new TextField(20);
add(input);
input.addActionListener(this);
f = new Font("Arial", Font.BOLD, 20);
}
publicvoid start()
{
//setSize(200,200);
setBackground(Color.white);
setForeground(Color.blue);
addMouseListener(this);
}
publicvoid actionPerformed( ActionEvent e )
{
command=e.getActionCommand();
//System.out.println("command= "+command);
repaint();
}
publicvoid paint(Graphics g)
{
for (index=0; index < command.length(); index++)
{
String temp = " ";
String c="p";
temp+=command.charAt(index);
if(temp.equals(c))
{
g.setColor(Color.red);
}
else
{
g.setColor(Color.green);
}
System.out.println("temp ="+temp);//for debugging
g.drawString(temp,xcord,ycord+10);//why "+10"? because it seemed like a good idea
xcord = xcord+=10;
}
}
// MouseListener event handlers
publicvoid mouseClicked( MouseEvent e )
{
xcord=e.getX();
ycord=e.getY();
paint(getGraphics());
repaint();
}
publicvoid mousePressed( MouseEvent e ){}
publicvoid mouseReleased( MouseEvent e ){}
publicvoid mouseEntered( MouseEvent e ){}
publicvoid mouseExited( MouseEvent e ){}
}
If you examine this part of code, you will notice that you are concatenating a character to temp. If the character you concatenate is 'p', then temp will have the value " p" (because of the space with which you initialized temp. Therefore your if condition fails.
NOW it works like I thought it would. Thank you!!! I was so worried about making sure I initialized everything, I totally overlooked what I was initializing things TO!