Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Java applet programming problem

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Java applet programming problem

    I am new to java and have been given a task of designing an applet that places the input string into a charcheter array and displays it. Also every letter "l" that appears must be displayed in red, and every letter "y" must be displayed in green. I have the following code but it doesn't work
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.Graphics;
     
    public class mix extends Applet implements ActionListener
    {
         Button okButton;
         String text1;
         public void paint(Graphics g)
         {
     
     		g.setFont (new Font ("Helvetica", Font.BOLD, 20));
     		g.setColor (Color.black);
     		g.drawString(text1,20,100);
     
     		if(text1.equals("l"))
                g.setColor (Color.red);
     		if(text1.equals("y"))
                g.setColor (Color.green);
        }
         public void init() 
         {
              setLayout(new FlowLayout());
              okButton = new Button("Enter Text");
              text1 = new String("",30);
              add(okButton);
              String(text1);
              okButton.addActionListener(this);
             }
            public void actionPerformed(ActionEvent evt) 
     
             {
                  if (evt.getSource() == okButton) 
                   repaint();
     
                  } 
             }
    Another thing I have to do is to be able to position the drawing point of the string with the mouse. I have no idea how to do any of this and any help will be appreciated. Thanks
    Last edited by copeg; March 3rd, 2011 at 02:29 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,661
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Java applet programming problem

    What is text1? e.g: is it the entire String or just a single character?

    You have to set the color of the Graphics object BEFORE you draw the String. If text1 is just an individual character, do the color setting before you draw the String. If text1 is an entire String and you want to go through each letter, put the color setting and the drawString inside a loop that will go through each character and change the color if it needs to. In this case, also put the color setting before the drawString call.

    Also, your action listener should probably set the text1 value to whatever the user entered.

    Lastly, for the mouse point, look into this: How to Write a Mouse Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Java applet programming problem

    Quote Originally Posted by aussiemcgr View Post
    What is text1? e.g: is it the entire String or just a single character?

    You have to set the color of the Graphics object BEFORE you draw the String. If text1 is just an individual character, do the color setting before you draw the String. If text1 is an entire String and you want to go through each letter, put the color setting and the drawString inside a loop that will go through each character and change the color if it needs to. In this case, also put the color setting before the drawString call.

    Also, your action listener should probably set the text1 value to whatever the user entered.

    Lastly, for the mouse point, look into this: How to Write a Mouse Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

    Thanks for the help, text1 is an entire string of any legth and the letters 'l' and 'y' need to be highlighted thoughout it. When using the above code and running it I get errors and when eclipse fixs these automatically there is no text box inserter on the applet. Dont suppose you could give me a small examle of this loop could you? As i said im very new to java and have no idea on what to do.

    Many thanks for all the above information.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,661
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Java applet programming problem

    You need to create a JTextField (JTextField (Java Platform SE 6)) and add it to the applet for the user to enter the text into. To create a simple JTextField (with 30 column length), use code like this:
    JTextField textField = new JTextField(30);
    And then you need to add the JTextField to your applet, in the same way you did your JButton.

    Then, in your Button Listener, you want to retrieve the text from the JTextField and set text1 accordingly. To do that, add something along the lines of this in your ActionListener:
    text1 = textField.getText();

    Lastly, since text1 is an entire String, when you paint it to the output you want to paint each letter individually, since you need to check if each letter is an l or a y. So you want to loop text1 and for each letter, check if the letter is an l, a y, or an other and set the color accordingly before you paint the letter.

    See how much of that you can do, and I'll help you with any issues you have.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    danielparry (March 4th, 2011)

  6. #5
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Java applet programming problem

    Thanks for that, I now have the following code (below) but when I run the program only a button appears with no text entry. I dont know what is causing this? Also I have never used loops before so I am also unsure on how to do this. I hope im not causing you a lot of hassle, but I am extremly grateful for your help.

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    import javax.swing.JTextField;
     
    public class textfield extends Applet implements ActionListener
    {
         Button okButton;
         String text1;
         JTextField textField = new JTextField(30);
         public void paint(Graphics g)
         {
     
     		g.setFont (new Font ("Helvetica", Font.BOLD, 20));
     		g.setColor (Color.black);
     		g.drawString(text1,20,100);
     
     		if(text1.equals("l"))
                g.setColor (Color.red);
     		if(text1.equals("y"))
                g.setColor (Color.green);
        }
         public void init() 
         {
              setLayout(new FlowLayout());
              okButton = new Button("Enter Text");
              text1 = textField.getText();
              add(okButton);
              okButton.addActionListener(this);
             }
            public void actionPerformed(ActionEvent evt) 
     
             {
                  if (evt.getSource() == okButton) 
                   repaint();
     
                  } 
     
        }

  7. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,661
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Java applet programming problem

    The reason there is no text is because the default text in a JTextField is "".

    There is a little change I would suggest to keep your code consistent and a few changes.

    First, since you initialized okButton in your init() method, you should initialize your JTextField there as well. So, we want this instead:
    Button okButton;
         String text1;
         JTextField textField;
         ...
         public void init() 
         {
              setLayout(new FlowLayout());
              okButton = new Button("Enter Text");
              textField = new JTextField(30);
              add(okButton);
              okButton.addActionListener(this);
             }
    ...
    }

    Now, the first problem we have is the JTextField is not added to our Applet. So, in order to add the JTextField to your applet, we do the same thing you did with your JButton:
    public void init() 
         {
              setLayout(new FlowLayout());
              okButton = new Button("Enter Text");
              textField = new JTextField(30);
              add(okButton);
    add(textField);
              okButton.addActionListener(this);
             }

    Now, we only want to set text1's value when the okButton is pressed. So, in our actionPerformed method we want to set text1. But it is also important to remember to set the value of text1 BEFORE we paint, since we will need the value of text1 in our paint method:
    public void actionPerformed(ActionEvent evt) 
             {
    text1 = textField.getText();
                  if (evt.getSource() == okButton) 
                   repaint();
     
                  }


    From there we can go through the text in the paint method. We can discuss that once you understand the above and get the interface working.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. The Following User Says Thank You to aussiemcgr For This Useful Post:

    danielparry (March 4th, 2011)

  9. #7
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Java applet programming problem

    Thank you so much for that reply, now I can insert text into the applet finally. Can we now do the paint and loops if you dont mind? Thank you so so much.

  10. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,661
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Java applet programming problem

    This part is pretty interesting because the only way I know to do it would be by splitting the String. However the problem with that is we need to offset each letter. And if we are going to offset each letter, the easiest way of doing it is by a constant value, but that will make the color String look weird when you have an offset for letters with small widths (such as l,i,j). A more complex way of doing it would be by getting the width of each letter and offsetting a constant number from the width of the previous letter. But that can be very difficult to understand.

    So, I guess I'll try to show both solutions.
    Now, the first thing we need to do is figure out where we want to start drawing the String. This will be an x and y coordinate. Later on we will want to set these x and y coordinates based on the mouse click, but for now let's just set an x and y value to work with. For simplistic reasons, we will use a x and y of 0. So, preferrably where we set our global variables we want to create:
    Button okButton;
         String text1;
         JTextField textField;
    int xCoord = 0;
    int yCoord = 0;
    ...

    Here is the code for the first way I explained. Read the comments and understand the code. If you are not 100% sure you understand a line of code or if you want to know why that code is needed, ask and I'll explain it for you.
    public void paint(Graphics g)
    {
    	//Set g's default Font and Color
    	g.setFont(new Font("Helvetica", Font.BOLD, 20));
    	g.setColor(Color.BLACK);
     
    	/* This is just an arbitrary value for determining how each letter should be offset.
    	 * Adjust this value to spread the letters or to decrease the space between the 
    	 * letters.
    	 */
    	int offsetValue = 10;
     
    	/* Loop through the length of text1. But, since we plan on substring, we want
    	 * to do less than the length minus 1, otherwise we will get an index out of
    	 * bounds issue on the last letter.
    	 */
    	for(int i=0;i<text1.length-1;i++)
    	{
    		/* To get the i'th letter of the text1 String, we need to use the 
    		 * String.substring(int,int) method. In this situation, we want to get
    		 * the letter that starts on the i'th index and ends on the index directly
    		 * after the i'th index.
    		 */
    		String letter = text1.substring(i,i+1);
     
    		/* Now we set the color based on the letter. For the below conditions, I
    		 * used the equalsIgnoreCase method instead of the equals method. You may
    		 * want to be case sensitive and if so, just use the equals method.
    		 */
    		if(letter.equalsIgnoreCase("l"))
    			g.setColor(Color.RED);
    		else if(letter.equalsIgnoreCase("y"))
    			g.setColor(Color.GREEN);
    		else
    			g.setColor(Color.BLACK);
     
    		/* Now we want to draw the String. Our Y value will not need to change, but
    		 * our X value will need to account for us offsetting i number of times.
    		 */
    		g.drawString(letter,(i*offsetValue)+x,y);
    	}
    }

    Now, let's say we want to use the other method I explained. This one is much more complicated and I don't really expect you to follow it (I barely understand it). You'll have to check to see if it even works because I haven't tried it.
    public void paint(Graphics g)
    {
    	//We want to create a font object because we will need it to calculate letter size
    	Font font = new Font("Helvetica", Font.BOLD, 20);
    	//Set g's default Font and Color
    	g.setFont(font);
    	g.setColor(Color.BLACK);
     
    	/* This is just an arbitrary value for determining how each letter should be spaced
    	 * from the previous letter. Adjust this value to spread the letters or to decrease 
    	 * the space between the letters.
    	 */
    	int offsetValue = 3;
     
    	// Value to store the width of our previous letter
    	int previousWidth = 0;
     
    	/* Loop through the length of text1. But, since we plan on substring, we want
    	 * to do less than the length minus 1, otherwise we will get an index out of
    	 * bounds issue on the last letter.
    	 */
    	for(int i=0;i<text1.length-1;i++)
    	{
    		/* To get the i'th letter of the text1 String, we need to use the 
    		 * String.substring(int,int) method. In this situation, we want to get
    		 * the letter that starts on the i'th index and ends on the index directly
    		 * after the i'th index.
    		 */
    		String letter = text1.substring(i,i+1);
     
    		/* Now we set the color based on the letter. For the below conditions, I
    		 * used the equalsIgnoreCase method instead of the equals method. You may
    		 * want to be case sensitive and if so, just use the equals method.
    		 */
    		if(letter.equalsIgnoreCase("l"))
    			g.setColor(Color.RED);
    		else if(letter.equalsIgnoreCase("y"))
    			g.setColor(Color.GREEN);
    		else
    			g.setColor(Color.BLACK);
     
     
    		/* Now we want to draw the String. Our Y value will not need to change, but
    		 * our X value will need to account for us offsetting by the previousWidth.
    		 */
    		g.drawString(letter,previousWidth+x,y);
     
    		//Adding to the previousWidth variable for each letter. This is odd and not sure if it works.
    		FontMetrics metrics = new FontMetrics(font){};  
    		Rectangle2D bounds = metrics.getStringBounds(letter, null);  
    		previousWidth += (int) bounds.getWidth()+3;
    	}
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  11. The Following User Says Thank You to aussiemcgr For This Useful Post:

    danielparry (March 4th, 2011)

  12. #9
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Java applet programming problem

    Thank you so much for that, I didnt check the second method but the first one worked fine. Eclipse didnt like: for(int i=0;i<text1.length-1;i++) so I had to change it to: for(int i=0;i<text1.length()-1;i++) Then I just changed the x to xCoord and set the amount and the y coord could be deleted and everything worked! Thank you so much. I have to submit this work by 5pm so if we coulddo the mouse listener then that would be amazing but if not do not worry, Thank you so much for your help I wouldnt have been able to do this without you haha.

Similar Threads

  1. Java mailer programming code problem
    By shadeslayer88 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 1st, 2010, 01:21 AM
  2. the infamous null pointer applet problem
    By wolfgar in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 22nd, 2010, 07:09 PM
  3. Problem with my animation applet
    By cBlue in forum Java Applets
    Replies: 1
    Last Post: December 9th, 2009, 06:49 PM
  4. Problem veiwing textfields in applet
    By danwoods in forum AWT / Java Swing
    Replies: 0
    Last Post: October 21st, 2009, 02:34 AM
  5. applet and JPS problem.... please help me
    By rockster14 in forum Java Applets
    Replies: 0
    Last Post: August 7th, 2009, 03:59 PM