• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strange !! Facing problem in a simple code

 
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guys,
Following is the code in which I am facing problem. There is a string which is initialized to 'John Levis says : This is something exciting'. Now I have to print this string on my applet by dividing it. So I took a substring and trying to first display until ':'. Then I have made up another string using substring, now I want to display that string on the same line where the earlier string was but it should be displayed where the previous string ended up. So I said - g.drawString(s1,25+s.length(),25);. The target output would be something like this : 'John Levis says : This is something exciting' but not by simply painting s. I have to split s first till ':', take rest of the string in some other string and then painting that another string.
For this I said - g.drawString(s1,25+s.length(),25);, but it seems drawstring method doesn't relies on length but on pixels. So tell me guys what can I do to solve this ?? Please help me. I would be obliged if someone can put up a code to do this !!
Thanks and regards,
/*<applet code="Test" height=200 width=200>
</applet>*/
import java.awt.*;
import java.applet.*;
public class Mitali extends Applet {
String s = "John Levis says : This is something exciting";
int i=s.indexOf(":");
String s1="";
public void init() {
s1=s.substring(i+1);
s=s.substring(0,i+1);
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,25,25);
g.drawString(s1,25+s.length(),25);
}
}
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use the stringWidth method of class FontMetrics.
public int stringWidth(String str) returns the advance width of the characters in the specified string.
try the following code:
<code>
public void paint(Graphics g)
{
FontMetrics fm = g.getFontMetrics();
g.drawString(s,25,25);
g.drawString(s1, 25 + fm.stringWidth(s),25);
}
</code>
 
reply
    Bookmark Topic Watch Topic
  • New Topic