Printing strings

Hello,
I have a problem printing in java.
Printing simple text trough g.drawString("printing text", x,x); goes fine,
but whenever I try to get text from a TextField printed I get the nullpointer.
When I press the print button the strings do have value, but I suspect I need to get the text out of the textfields somewhere different in my application.
This is what I've got so far, note: printing the typed strings works well, but when printing from my java strings
it won't work. I have also documented these things in the code below.
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException
          strFirstname = txtFirstname.getText();  // Where I get the value from the textfields
          strLastname = txtLastname.getText();
      if (page > 0)
      {           // We have only one page, and 'page' is zero-based
           return NO_SUCH_PAGE;
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pf.getImageableX(), pf.getImageableY());
          g.drawString ("First name:", 0, 75); //These lines get printed perfectly.
          g.drawString (strFirstname, 115, 75);
          g.drawString ("Last name:", 0, 100); //This line is getting printed perfectly aswell.
          g.drawString (strLastname, 115, 100);
          return PAGE_EXISTS;
}And the code from the print button:
    private class PrintHandler implements ActionListener
         public void actionPerformed (ActionEvent e)
         PrinterJob job = PrinterJob.getPrinterJob();
             Book book = new Book();
         PageFormat documentPageFormat = new PageFormat();
         documentPageFormat.setOrientation(PageFormat.LANDSCAPE );
         book.append(new frmModify(), documentPageFormat); // frmModify = the class wich extends the frame and implements PrintAble.
         job.setPageable(book);
         System.out.println(strFirstname); // The values of the strings get printed perfectly IN THE CONSOLE, not on paper.
         System.out.println(strLastname);
         boolean ok = job.printDialog();
         if (ok)
             try
                  job.print();
             } catch (PrinterException ex)
              /* The job did not successfully complete */
                  ex.printStackTrace();
    }

I might have come closes to the answer but I'm not there yet !
When I use this piece of code in my constructor (where the textfield is made)
txtFirstname.setText ("Derek");
txtLastname.setText ("Jeter");The string in the print method ain't null anymore but it prints correctly "Derek" and "Jeter" in the console.
So it might has something to do with the print method being called before the textfields are actually called by my stored procedure.
This is how I call the frame:
                fmod = new frmModify();
                fmod.vernieuwOfficeCC(); // Renewing my choice menu's.
                fmod.vernieuwBusinessUnitCC(); // Renewing my choice menu's
                fmod.showUser(oFirstname, oLastname, oJobtitle, oDepartment, oPersref, oOffice, oBusinessUnit); //This is where they fill the text fields with data.
                fmod.openWindow(); //Method with setVisible(true);Actually it has to be in the way I call the frame and methods. I just can't figure it out at the moment.
Because when the constructor frmModify() is called the text fields are empty because they won't get filled until showUser();.
Any idea how I fix this ?
Edited by: Nimzor on Mar 10, 2008 6:08 AM

Similar Messages

  • Use of formatting when printing strings

    I would like to know how to print a string that is italicized. I am open to ideas involving complicated methods .. good to learn something new.

    831334 wrote:
    Well I am a graduate student in Computer Science currently building from scratch a database program as part of my school database class I am taking this semester. I have taken undergraduate courses in Java covering simple types, and data structures; at the graduate level algorithm analysis covering topics such as Fourier Transforms. I am also engaged in improving my C programming skills and learning Python to boot.Well that's nice for you, but I doubt many will be impressed here.
    When I originally posted I thought I would receive an answer to my question regardless where I posted; perhaps this forum would be more active and relevant for my question. Now that my resume is out there including a background in electrical engineering, should I hit Google or can I get an answer to my question?Now I know that one shouldn't expect much eloquence from a computer scientist, but your original question of "How can I print Strings in italics" wasn't exceptionally well thought out. Or was it news to you that Java is capable of outputting Strings in more ways than outputting to a standard console?
    If not the current adage is: "Its easy, just Google it" will suffice and follows the wade through data overload but oh well.We gave you plenty of answers already, do we need to hold a lecture for you to understand them?

  • Print string array

    Hi
    for printing numbers, I would do this:
    for (int x=0; x<=myArray; x++)
    System.out.prin(x);
    But How would I do for printing String values I have read in to a string array?
    I have read in som names to a string array and can print them by:
    System.out.print(myarray[0] + myArray[2]);
    This would print index 0 and 2 in the array. But this is not so good if you have an index large as 100 for example. So how would i go thru the String array and print out the variables?
    Martin

    dream77 wrote:
    case 2: // Print out the list
                        for (int x=0;x<arrNames.length; x++)
                             if (x < nameCount)
                             System.out.print(arrNames[x]);
    1) ALWAYS enclose for loop and if statements in curly braces, even if it's only one statement. So don't do either of these:
    if (fubar ==3)
        doThis();
    // and
    for (int snafu = 0; snafu < myLength; snafu++)
        doThat();instead write:
    if (fubar ==3)
        doThis();
    // and
    for (int snafu = 0; snafu < myLength; snafu++)
        doThat();
    }You'll thank me for this later.
    2) If nameCount is less than arrNames.length always, why use this as the exit condition in your for loop? i.e.,
    for (int x = 0; x < nameCount; x++)
        System.out.print(arrNames[x]);
    }

  • Print string to client printer using applet

    How to print a string directly to the client printer after clicking a button from my jsp/html page?
    I have posted a similar question here and someone(pqeuens) advised to use applet. I have been reading about applet & created one.
    I tried running it as a Java application & it prints as expected. However when i put it inside a jsp/html page, it will not print.
    Can anyone help me out on this? Perhaps share a code. That will be very much appreciated...
    Thank you

    I said you couldnt just print from JSP but you might be when you use a SIGNED applet.
    But then you need to move to the java applet forum and ask question there.
    Furthermore a standard applet cannot print because of the security invloved in applets. Nor will you be allowed to write files onto the client.

  • Printing Strings on same line questions

    I need to know how to print the same number of _ (underscores) as there are letters in a given string. I already have the int of the number of characters in the string but how do i use that to print the same number of underscores in ONE line, not vertically. responses are appreciated.

    In your loop that prints the underscores, use System.out.print("_"), rather than System.out.println("_"). Read the javadocs to see the difference between these two methods.

  • Print string char by char

    Hi,
    I need to know if it possible, and how to send a string message to the printer and control the print from the keyboard.
    I will explain:
    A known text should be print by the printer in a way that each key press (spacebar or other key) will command the printer to print the next char.
    i.e the text is "Hello World", the first space bar hit will result "H" on the printer paper, the second spacebar hit will result "e" on the printer paper and "He" is the the current string printed... etc.
    if you think its possible or if you know how to do it, I will be happy if you share it with me.
    Thanks.

    If you're interested in this sort of thing, the following may be of help:
    A Demonstration: Using the Java� Print Service API
    Printing in Java, Part 1: Acquaint yourself with the Java printing model
    The Java� Tutorial - I/O: Reading and Writing (but no 'rithmetic)

  • Size of printed String

    Hi
    String s = "Hello";
    System.out.println(s+"\t"):Is there any method to learn the size of Strings "in relation to Tabs".
    I'm trying to pretty print at standard output some list of strings of different length and it gets messy
    Array size = 3600
    assassi     assass�     assassui     assass�
    assachi     assach�     assachui     assach�
    assazi     assaz�     assazui assaz� (crap here)
    assessi     assess�     assessui     assess�
    Like that.

    You can use FontMetrics.getStringBounds() or use TextLayout
    ================================
    Sincerely,
    Melnikov V
    AlarIT programmer
    http://www.AlarIT.com
    ================================

  • Printing Strings in SAP Scripts

    Hello
    I need to print a string in Script that is not defined anywhere in the script.
    example, I need to print 60 CAD/ 100 LE.
    I have text symbols for all these(60,CAD,100,LE) values except '/'.How can I print this in Script. Help me with the syntax.
    Thanks
    Tharani

    Maybe you can try this:
    /: DEFINE &CH1& = '60'.
    /: DEFINE &CH2& = 'CAD'.
    /: DEFINE &CH3& = '100'.
    /: DEFINE &CH4& = 'LE'.
    /: DEFINE &LOM& = '/'.
    /: DEFINE &CH& = '&CH1& &CH2& &LOM& &CH3& &CH4&'.
    /  &CH&

  • Need help, trying to print strings backwards while ignoring certain things.

    To clarify the topic what I mean is I want to spell the words the user inputs backwards while skipping over certain characters. Here's my code:
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.io.*;
    class SConvert{
    private static final char BLANK = ' ';
    private static final String stop = "STOP";
    public static void main(String[] args){
    char[] ignore = new char[21];
    ignore[0] = '.';
    ignore[1] = '/';
    ignore[2] = '>';
    ignore[3] = '<';
    ignore[4] = ',';
    ignore[5] = '?';
    ignore[6] = '-';
    ignore[7] = '~';
    ignore[8] = '!';
    ignore[9] = '@';
    ignore[10] = '#';
    ignore[11] = '$';
    ignore[12] = '*';
    ignore[13] = '&';
    ignore[14] = '^';
    ignore[15] = '%';
    ignore[16] = '`';
    ignore[17] = '_';
    ignore[18] = '+';
    ignore[19] = '=';
    ignore[20] = '|';
    String word, statement, append;
    boolean go = true;
    int i, numOfchar, index;
    char[] chr;
    index = 0;
    word = " ";
    statement = " ";
    append = " ";
    Scanner scanner = new Scanner(System.in);
    while (go){
    System.out.println("Enter a word");
    word = scanner.next();
    chr = word.toCharArray();
    numOfchar = word.length();
    if (word.equals(stop)){
         break;
    else if (index < numOfchar && word.charAt(index) == BLANK + BLANK){
         index = BLANK;
    else if (index < numOfchar && word.charAt(index) == (int)ignore[19]){ //Trying to range for entire array, I don't know how.
         index++;
    else
           for (i = word.length() - 1; i >= 0; i--)
              statement = statement + chr;
              append = append + " " + statement;
    System.out.print(append + " ");
    What's messing me up is the fact that whenever I try to enter words into the program, printing append only repeat EVERY occurance of statement. For example, say I type in "Ham with gravy." I get "maH htiwmaH yvarghtiwmaH".
    That's not what I want. Also, I don't know how to make the entire array of ignore available to the program, anyway to do that?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Wow. What's with the hostility? Even I was in error of detecting anything that could have solve the problem completely there's no need to use such a negative tone, epsecaility with someone who is learning to program in OOP, let alone the syntax of Java. Also, no your program did not solve all of my problems in it's original form. Let's take a look at it.
    Here's your code:
    import java.lang.String;
    import java.util.*;
    public class ReverseString {
      public void ReverseString(){
      public void printReverse(String s){
         int i;
        String noPrint = "no print'";
        char ch = '*';
        if(s.length()>1) printReverse(s.substring(1));
         ch = s.charAt(0);
        if (!noPrint.contains(ch + " ")) System.out.print(ch);
        return;
      public static void main(String[] args) {
          String myString = Here is my String.;
       System.out.print("My String: " + myString + " Reverse: ");
       new ReverseString().printReverse(add);
       System.out.println();
    }In it's original state the program doesn't allow for any user input, which is something I needed (and added on my own), it doesn't convert the ignore[] I had in my original code to anything readable (however this can be done in the noprint String quite easy as someone else mentioned earlier.) the if command does in fact ignore the special characters in noprint String HOWEVER it doesn' t not print those characters as they would appear in the myString String in the position that it original appeared in (which is the primary problem I am having.) That is the problem with your code and why it is not the complete to soultion to my homework problem. I've modified your code to satisifed all but one of the problems.
    Modified:
    import java.lang.String;
    import java.util.*;
    public class ReverseString {
      public void ReverseString(){
      public void printReverse(String s){
         int i;
        String noPrint = "~`!@#$%^&()-=+[{]}\':;?/>.<,'";
        char ch = '*';
        if(s.length()>1) printReverse(s.substring(1));
         ch = s.charAt(0);
        if (!noPrint.contains(ch + " ")) System.out.print(ch);
        return;
      public static void main(String[] args) {
           Scanner scanner = new Scanner(System.in);
          String myString;
          String add = " ";
           while (true) {
       System.out.println("Please input String.");
       myString = scanner.next();
       add = add + myString;
              if (myString.equals("STOP")){
                   break;
       System.out.print("My String: " + add + " Reverse: ");
       new ReverseString().printReverse(add);
       System.out.println();
    }If you run this code you'll see what am talking about. The only remaining problem, which I am about to restate if you are still unclear of it, is that the noprint String contents are ignored but not printed in the original position. If you are still having trouble understanding what I am talking about then let me show what I got by running the program.
    String: Ham with grav?y
    Reverse: yvarg htiw maH. [Note the ? is missing.]
    By removing the ! in the if command I get:
    Reverse: y?varg htiw maH. [Now the ? is in the wrong position.]
    It's suppose to be:
    String: Ham with grav?y
    Reverse: yvarg htiw ma?H.
    Secondly, I understand that you are frustrated with my apparent lack of understanding of proper Java tems and syntax but you must keep in mind I am student thus I am not fully aware of java as you are. With that one would expect you to act with a bit more patience, yet you not only took offense to an innocent comment you choose to slander my name and intelligence by erasing your code and calling my understanding of Java, ?ignorant.? I may be less than careful with my choice of words concerning Java but I do understand enough code to know the inner workings of a typical program, so please refrain from calling me ignorant or any variant of this in the future.
    I merely asked for help from general populous, do not think I owe you any particular praise for your code even if I find it is not exactly what I desired. I may be new to java but I am not new the message boards. With that said I find your response awfully rude and ask if you to refrain from do so in the future. I'm assuming you are an adult so act least act like someone with a bit of civility. If you were so committed to believing your code was the de facto solution to this problem then you could have simply asked why I say what I said, if had done so and shown me the error of my statement I would have not taken offense. Instead you choose to throw a fit and deleted your code. I do not know if you are like this around other board members but you should at least show courtesy to all members of this forum regardless of their time here.
    With that said, I think I've all ready found a solution to this problem I've had. I'll just tell the program to simply count over the position the character is in. That way it will stay in the same position.

  • How to make new-line when printing strings?

    Please help me with code . I can't able to print the string in new line
    Anil

    ... the same question as your other post:
    Printing the string

  • What tag to use to print STRING value from Backing Bean

    Hi;
    I would like to achieve the objective as below:
    Displaying 4 buttons (pagination) in my jsf page:
    1) Go First
    2) Go Previous
    3) Go Forward
    4) Go Last
    <h:commandButton image="images\first(on).gif" type="submit" action="#{alertSetBean.goFirst}"/>
    <h:commandButton image="images\previous(on).gif" type="submit" action="#{alertSetBean.goPrevious}"/>
    <h:commandButton image="images\forward(on).gif" type="submit" action="#{alertSetBean.goForward}"/>
    <h:commandButton image="images\last(on).gif" type="submit" action="#{alertSetBean.goLast}"/>In order to make sense for user, when the page is displaying first set element records, the icon should be disabled for
    -Go First
    -Go Previous
    and same goes to last set element records, icon to disable for
    -Go Forward
    -Go Last
    To disable, i will substitute
    <h:commandButton image="images\forward(on).gif" type="submit" action="#{alertSetBean.goForward}"/>
    with
    <h:graphicImage value="images\previous(off).gif" />
    It looks very messy in jsf page. Therefore, I would like to call a method in Backing Bean, where it will do check pagination by returning the long string as following:
    <h:commandButton image="images\first(on).gif" type="submit" action="#{alertSetBean.goFirst}"/>
    <h:commandButton image="images\previous(on).gif" type="submit" action="#{alertSetBean.goPrevious}"/>
    <h:commandButton image="images\forward(on).gif" type="submit" action="#{alertSetBean.goForward}"/>
    <h:commandButton image="images\last(on).gif" type="submit" action="#{alertSetBean.goLast}"/>Unfortunately, i'm using
    <h:outputLabel
    <h:outputText
    The JSF page DOES NOT render the code, and it print the string instead. Please, I need advise.
    Thanks;
    Yoke Yew

    Hi Balu;
    Before i received your great response, i was in the midst debugging
    Servlet.service() for servlet jsp threw exception
    org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
    with my following JSTL code
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
    <tr>
           <td align="right">            
                </f:verbatim>
                <h:outputLabel value="#{alertSetBean.totalCnt}" styleClass="lbl"></h:outputLabel>
                <h:outputLabel value="  Total  " styleClass="lbl"></h:outputLabel>
              <c:if test="${alertSetBean.pagination == 1}">
                   <h:graphicImage value="images\first(off).gif"/>
                <h:graphicImage value="images\previous(off).gif" />
                <h:commandButton image="images\forward(on).gif" type="submit" action="#{alertSetBean.goForward}"/>
                <h:commandButton image="images\last(on).gif" type="submit" action="#{alertSetBean.goLast}"/>
              </c:if>          
              <c:if test="${alertSetBean.pagination == 2}">
                   <h:commandButton image="images\first(on).gif" type="submit" action="#{alertSetBean.goFirst}"/>
                <h:commandButton image="images\previous(on).gif" type="submit" action="#{alertSetBean.goPrevious}"/>
                <h:commandButton image="images\forward(on).gif" type="submit" action="#{alertSetBean.goForward}"/>
                <h:commandButton image="images\last(on).gif" type="submit" action="#{alertSetBean.goLast}"/>
              </c:if>
                <c:if test="${alertSetBean.pagination == 3}">
                     <h:commandButton image="images\first(on).gif" type="submit" action="#{alertSetBean.goFirst}"/>
                <h:commandButton image="images\previous(on).gif" type="submit" action="#{alertSetBean.goPrevious}"/>
                <h:graphicImage value="images\forward(off).gif"/>
                <h:graphicImage value="images\last(off).gif" />
                </c:if>
                <f:verbatim>
           </td>
      </tr>I hope somebody can point where is my mistake, and i will refer to your previous solution suggested. Thanks in advance.

  • Load String into CharArray and then Print String in Reverse?

    Hey, what would the code be to:
    1. Ask user for name. (scanner)
    2. Load his name into a CharArray.
    3. Then print out his name backwards.
    thanks a lot!

    dforevergold has a head on his neck. So, I don't understand people saying about assignments etc... If he needs help and we can help then we must help.
    Here's the code (but don't forget about comments!):
    import java.util.Scanner;
    public class Just {
         public static void main(String[] args) {
              // a scanner to get user's input
              Scanner scan = new Scanner(System.in);
              // Scanner.nextLine() returns the entered line
              String name = scan.nextLine();
              // toCharArray() converts a 'String' object to a 'char[]' object
              char[] ch = name.toCharArray();
              // next FOR-loop goes from the last element in the array to the first one and prints them onscreen
              for (int i = ch.length - 1; i >= 0; --i) System.out.print(ch);
    I hope it helps you!
    Yours Sincerely,
    Nikaustr

  • Print string in Smart Form

    hi, i have a problem while print long string in smart form.
    If the string is too long to display in one line,
    it is split into another line.
    However, the words are also split into two lines.
    For example,
    my string is "this is a long string",
    when it is printed , it become
    "this is a lo
    ng string"
    Does anyone know how to solve this problem?
    Would u pleas tell me, thanks a lot.

    Hi,
    U better to maintain standard text in SO10
    Then call the text into the SF.
    I think it will work
    Regards,

  • NullPointerException on out.print (String)

    I am using weblogic 4.5.1 and jsp 1.1
              Within a jsp page:
              <% out.print (someString); %>
              When someString is null, the server is throwing a NullPointerException.
              The stack trace reveals that the server is trying to do a
              someString.length() call (Whatever for?). Must you check every string that
              you print our for null before you print it?
              Thanks for the help.
              Tim
              

    The 'New to Java' forum is some doors further. Please make use of it for basic questions about the Java SE API which are in fact already answered in the javadocs. This has completely nothing to do with JSP/Servlet.

  • Printing strings to file

    Hey all :-)
    I'm trying to get an app to output strings to a file (log) but for some reason it's not working... yes this is the first time i've ever had to output strings.
    I've tried setting variables:
    File outputFile = new File("Output.log");
    FileWriter out = new FileWriter(outPutFile);And then writing to them:
    String username = userNameField.getText();
    char[] usernameToChar = username.toCharArray();
    try {
      for(int i = 0; i < usernameToChar.length; i++)
        out.write(usernameToChar);
    } catch(IOException exception) {
    System.out.println("Error writing to file!");
    But this isn't working.
    Can someone please let me know what i'm doing wrong?

    A number of suggestions:
    1) "It's not working" is not real descriptive. Explain exactly what you want to happen and exactly what is happening instead. If there's an error message, post it.
    2) When you get an exception, don't just print your message like that--let it tell you some details about what went wrong, with exception.printStackTrace().
    3) Use a PrintWriter wrapped around a FileWriter to write a line at a time, rather than writing a character at a time. FileWriter fw = new FileWriter(outputFile);
    PrintWriter pw = new PrintWriter(fw);
    pw.println(username); or something like that--look at the docs for details.
    4) I'm guessing that your problem is that you're not calling flush(). Try it, just for closure, and then move on to the PrintWriter.
    &para;

Maybe you are looking for

  • Disable "Display PDF in browser" | Acrobat, Reader XI

    I understand this is the suggested method of disabling the "Display PDF in browser" is  http://helpx.adobe.com/acrobat/using/display-pdf-browser-acrobat-xi.html    However we would like to know if there is an API or something we can simply remove fro

  • Printing Form Header Text in Smartforms

    Hi, I have created smartform for SD module.I am printing Form header text in a window by using loop.I am getting the text with the help of READ_TEXT  function module.It comes as we type in Form header.But the problem is if they type more than 15 line

  • How do I enable EAX and S

    I have the c00 player the creative media organizer came with it and was looking through some of the features and the SVM looks very interesting. However when I go to enable it, its greyed out. I have already scanned all my music, do I need to have a

  • PSE-6.......assigning file types (jpeg, TIFF, psd)

    I mistakenly contacted Canon regarding the following question, and they said it was a matter of my photo editing software. I'm reading articles about editing photos for jewelry photography.  The articles I'm reading say to start off as a TIFF or PSD

  • Problem with Oracle Net configuration

    OK this should be simple but I'm not seeing it. I have a database listener that runs on port 1530. I think that I have all of the networking files configured correctly and the database configured correctly yet but I'm still getting the following erro