Why imageComplete is called twice!

I wrote the following code:
public class Test{
public static void main(String[] args){
//get image
Image image = Toolkit.getDefaultToolkit().createImage("javalogo.gif");
ImageConsumerImpl impl = new ImageConsumerImpl();
//get image producer
ImageProducer ip = image.getSource();
// start production
ip.startProduction (impl);
//wait here
class ImageConsumerImpl implements ImageConsumer{
// other methods are "null"
public void imageComplete(int status){
System.out.println("Status:"+status);
This code did not behavior as I had expected. I thought imageComplete could be called for only once. But it will be called twice, value status is 3(STATICIMAGEDONE) for the first time, but 1 for the second call, which indicates an image error.
I don't know why, can you give me the answer? javalogo.gif is a static picture.

pls help me with this, thanks

Similar Messages

  • Why valueChaged( ) method called twice

    Dear All,
    I have made a class MyList by extending JList and implements ListSelectionListener and override valueChanged method. When we clicked on the list item this method called twice. Can you please explain the region?
    I write my code like that:
    Public void valueChanged(ListSelectionEvent lse)
    System.out.println(�Hello�);
    Out put:
    Hello
    Hello
    Thanks
    Bipin Kuma

    It's expected - check the details and you'll see why.
    If, say, the user had selected item 3 and then select item 8 then you might get two events:
    1. first 3, last 3, isAdjusting true
    2. first 8, last 8, isAdjusting false
    It's a poor event protocol if you ask me but there you go.

  • Urgent, please help. why the ListSelectionListener() called twice?

    I had two JList, and every time, I click value in list1, it will call the ListSelectionListener() twice, and when I click on value in List2, it called the list2 actionListener twice also, I don't know why?
    Please help.
    The part of the code list below:
    jList1 = new JList(words1);
    JScrollPane scrollPane1 = new JScrollPane(jList1); jList1.setBackground(Color.lightGray);
    jList1.setBorder(BorderFactory.createLoweredBevelBorder());
    jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
         jList1_valueChanged(e){
    /* add Column_Name to the jList2*/
    JScrollPane scrollPane2 = new JScrollPane(jList2);
    jList2.setBackground(Color.lightGray);
    jList2.setBorder(BorderFactory.createLoweredBevelBorder());
    jList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    jList2_valueChanged(e);
    void jList1_valueChanged(ListSelectionEvent evt)
    void jList2_valueChanged(ListSelectionEvent evt)
    {     }

    You can call ListSelectionEvent.getValueIsChanging() to find out if the selection is in progress or if has been finished. You will get an event both when the user starts the selection (presses the button) and when he/she finishes it (lets go of the betton).
    /Michael

  • Why listener methods are getting called twice ?

    Hi Group,
    I have a doubt, i need to know logic behind it.
    Lets consider, JComboBox,
    For an item state change of JComboBox,
    itemStateChanged method gets called twice.
    Its similar with valueChanged getting called twice
    on List Selection Event.
    Why does it call twice ? Is there any way, I can
    have invocation only once (except flagging mechanism)?
    with regards,
    vikram.

    http://java.sun.com/j2se/1.3/docs/api/java/awt/event/ItemListener.html
    tells the following:
    public void itemStateChanged(ItemEvent e)
    Invoked when an item has been selected or deselected. The code written for this method performs the operations that need to occur when an item is selected (or deselected).
    So the listener is notified for both items: losing and gaining selection.
    If you are only interested in listening to either selection or deselection event you can check which was the cause for the method call by examing the ItemEvent parameter i.e. item_event.getStateChange() == ItemEvent.DESELECTED or ItemEvent.SELECTED and then decide whether you are interested in the event at all.
    I don't know how to stop JComboBox from launching both select and deselected events.

  • PrepareForDML method called twice

    Have implemented a typical scenario (search - add - edit jspx pages).
    Within one application module, one view object with dynamically created where criterion is used for searching, and another view object fetching at most one row is used for inserting/updating. The second view object is based on a join of an updatable entity (that has as primary key trigger-generated sequence number) and several referenced readable entities that bring descriptions of the codes of the updatable entity. Have implemented descriptions as output fields in the jspx, settign partialTriggers to the id of the code-field of the updatable entity having autoSubmit=true. Have concentrated business validation logic within the prepareForDML() of the updatable entity implementation.
    Under normal conditions, it works fine.
    Under heavy system load in production, or testing with ADF State Management enabled at work environment, I observe the prepareForDML() called twice instead of once.
    Thus, the first time the insert is commited, the second time the validation rollback, and at last the whole transaction is rollbacked.
    When I commented-out all the fields that bring descriptions and set all autoSubmit=false, prepareForDML() was called once.
    However, my problem is that I have to bring the descriptions, that result from pop-up windows so that the end-user can see them after selecting sthg on his/er screen.
    Why is prepareForDML() called twice, and how can I avoid this?

    (2) Can't change the second trigger-assigned field from DBSequence to simply Number since the Entity Object Editor hides the tab Sequence to declare the sequence from which to get this field's value after insert.
    Please see section "6.6.3.8 Trigger-Assigned Primary Key Values from a Database Sequence" of the ADF Developer's Guide for Forms/4GL Developers on the ADF Learning Center at http://www.oracle.com/technology/products/adf/learnadf.html for more information on this. The "Sequence" tab doesn't have any runtime behavior influence. The sequence number is not assigned by ADFBC, it is assigned by your trigger. ADFBC only worries about:
    1) Providing a temporary unique negative key so that new detail rows can have a temporary foreign key value to point at until the transaction commits
    2) Refreshing the entity object's primary key value from the database-trigger assigned sequence number (however, we really don't know how the trigger populated the value) Theoretically, it may or may not have used a database sequence to assign the number. It would work just the same at the ADFBC level)
    3) Refreshing the temporary negative foreign key values in newly-created detail rows for new, composed details of the new composing master row with the definitive primary key value.
    So, you should safely be able to change this to a Number, with its Refresh after Insert property set.
    (3) Create() on entity implementation was always called once at page load, unexpectedly prepareForDML() always carried on two consequtive rows (either the new row to insert twice or the query's first row retrieved to update and afterwards the new row to insert) having State Management enabled.
    If create() is being called only once, then next you should check the value of the "operation" flag that is passed to prepareForDML() to understand if the method is being called for DML_INSERT or DML_UPDATE. Perhaps somehow an existing row is being inadvertently updated so one of the calls to prepareForDML() might be an update? I don't understand how prepareForDML() could fire twice for two new entity objects if the entity object's create() method is only called once. If you have a testcase that illustrates this, please report it to Worldwide Support via Metalink so they can triage and file a bug for you on it.
    (4) Swapping selectInputText components with SelectOneChoice, thus avoiding the partial page rendering, I managed prepareForDML() to function logically so that to have only one row to insert, but again since I have validation code in my entity implementation that throws JBO-exceptions, another problem occured. The first time the end-user receives an exception (e.g. invalid Tax Number), the second time he/she corrects it, the created row instance at prepareForDML() doesn't get updated with the new valid Tax Number, but continues to hold the old value at second run. To remind that if insert is successful the navigation moves on to the update page, otherwise it remains at the same (navigation outcome is null).
    Are you absolutely sure in this case that a second new row is not getting created?

  • ItemListener calls Twice

    Hi,
    I am having a ComboBox and when I select an Item, my listener calls twice.
        cmbInputSource.addItemListener(new java.awt.event.ItemListener() {
          public void itemStateChanged(ItemEvent e) {
              setInputSource(cmbInputSource.getSelectedItem().toString());
        });Thats my code, I am using this code in my Constructor, but I still dont find why this method calls twice.
    Any Ideas?
    Thnx

    Great job ��we define this not a bug, but a feature :/
    Or is anyone serious that it is good API design to make a method name look self-explanatory, but have an important detail hidden in the documentation?
    The unnecccessary double call of event listeners may potentially decrease the perceived performance of the system by 50% ��this shouldn't be a favourite solution.
    I searched the bug database for an "RFE" concerning this point, didn't find one. However I don't file one, as I don't have a simple test code at hand to demonstrate the problem.
    Martin

  • JComboBox  itemStateChanged gets called twice.

    Hi i have a JComboBox whoes itemStateChanged gets called twice. I have taken a look at other post concerning this topic and non have worked for me . I will greatly appreciate it if someone can help me
    here is the code !!!!!!!!!!
    jComboBox3.addItemListener(new ItemListener(){
    public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange() == e.SELECTED){
    jComboBox3_dosomething(e);
    thanks in advance

    Maybe this thread will answer why it gets called twice:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=257226

  • HELP!!! why derived class's function  be called twice?

    I am a newbie to java.
    Recently I encounter a problem.
    I run the below file,the output is:
    output begin
    B.f called !!!!
    A.A called
    B.f called !!!!
    B.B called
    output end-
    My Question is :
    why B's f() be called twice?
    (In C++, A.f() will be called one time!)
    class A
    A()
    f();
    System.out.println("A.A called");
    int f()
    System.out.println("A.f called !!!");
    return 123;
    class B extends A
    B()
    f();          
    System.out.println("B.B called");
    int f()
    System.out.println("B.f called !!!!");
    return 456;
    public class Demo
    public static void main(String args[])
    B bobj = new B();
    -----------------------------------

    Hi,jsalonen:
    In the following code, variable i cann't be initialized properly.
        class A
             int i=0;
            A()
                f();
                System.out.println("A.A called");
                System.out.println("i="+i);
            int f()
                i=11;
                System.out.println("A.f called !!!");
                return 123;
        class B extends A
             int j;
            B()
                f();                  
                System.out.println("B.B called");
                System.out.println("j="+j);
                System.out.println("i="+i);
            int f()
                j=12;
                System.out.println("B.f called !!!!");
                return 456;
        public class Demo
            public static void main(String args[])
                B bobj = new B();
    output begin
    B.f called !!!!
    A.A called
    i=0 // BAD here
    B.f called !!!!
    B.B called
    j=12
    i=0 // BAD here
    output end -
    Although the question can be solved! I am still confused: why Java do this? when A's constructor call f(), B is still incomplete!!
    Java is a good language,but I dislike it on this
    Regards.
    Sunway

  • Why is the ActionForms validate-Method called twice?

    Hello forum,
    I'm new to struts and want to develop a form, where an internetuser can leave a comment to an article. Just like most sides, an image with an text is displayed, the text has to be written into an inputfield before the comment is commited in order to be saved.
    When an user puts in no text or a wrong one, a errormessage is displayed, the old image is deleted and an new one is created and shown to the user. His input still stays in the fields.
    I proof the correctness of the word in the validate-Method of the ActionForm and it works fine.
    Now I've the following problem:
    If the user puts in the correct text, the comment is saved and the side is displayed again including his comment.. But also all the input of the form should be erased. But for some reason, its not and the validate method is called again and since there is a new wordvarifyingimage and a new text to be inserted, it throws an error which is displayed again. Also, all the input of his last message is present!
    So, I guess I miss a big point about the ActionForm handling. Why is the ActionForm called twice and why doesn't it erase the old input? I try to do this in the Action class after saving the comment, setting all the formparameters to "" or null.
    Can anybody give me a hint?
    Would be a big big help since I've not found anything googling about this issue.
    If you need code, just tell me which part I put in here (ActionForm, Action, struts-config or jsp-file)
    Thanxs in advance,
    strutsnewbytopro

    my jsp:
    <%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="struts/html-el" prefix="html" %>
    <%@ taglib uri="jstl/c" prefix="c" %>
    <%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <style type="text/css" title="currentStyle" media="screen">
              @import "../library/css/blog.css";     
         </style>
    <script language="javascript">
         function sendMail(){
              document.forms[0].formaction.value ='mail';
              document.forms[0].submit();
         function saveComment(){
              document.forms[0].formaction.value ='comment';
              document.forms[0].submit();
         </script>
    </head>
    <body>
    <html:form action="/blog">
    <div id="container">
         <div id="leftside">
              <logic:messagesPresent>
                   <div id="errors">
                        <div style="color:#CC3333; ">
                        <p><span id="errorHeaders"><bean:message key="errors.validation.header"/></span>
                             <html:messages id="error">
                             <c:out value="${error}"/>
                             </html:messages>
                        </p></div>
                     </div>
              </logic:messagesPresent>
                 .... show blogentry ...          
              <logic:present name="comments">
                   <div id="divblogcomment">
                   <logic:iterate name="comments"  id="com">
                   <div class="breaker10" style="clear:left; "></div>
    <div class="rowblogcommentdate" style="width:150px;"<a href="<bean:write name="com" property="website" />"><bean:write name="com" property="username" /></a> am <bean:write name="com" property="postdate" /></div>
                   <div class="rowblogcomment"><bean:write name="com" property="comment" /></div>
                   </logic:iterate>
                   <div class="breaker10" style="clear:left; "></div>
    </div>
              </div>
                             </logic:present>
                             <logic:notPresent name="savedcomment">
                                  <div id="writeblogcomment">
                                  <div class="topbig"><div class="headsmall">enter Comment</div></div>
                                  <div id="bginhaltwriteblogcomment">
                                       <div class="breaker10" style="clear:left; "></div>
                                       <div align="center">
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                 <tr>
                                                      <td>Name:</td>
                                                      <td>  </td>
                                                      <td><html:text size="50" name="blogForm2" styleClass="inputtext" property="username"/></td>
                                                      <td>  </td>
                                                      <td>Web:</td>
                                                      <td>  </td>
                                                      <td><html:text size="50" name="blogForm2" styleClass="inputtext" property="webaddress"/></td>
                                                 </tr>
                                                 <tr>
                                                      <td>Enter Code:</td>
                                                      <td>  </td>
                                                      <td><html:text size="66" name="blogForm2" styleClass="inputtext" property="commentword"/></td>
                                                      <td>  </td>
                                                      <td >Code:</td>
                                                      <td>  </td>
                                                      <td><img src="<bean:write name="entry" property="commentpicurl" />"></td>
                                                 </tr>
                                                  <tr>
                                                      <td colspan="7">Comment<br><html:textarea name="blogForm2" styleClass="comment" property="comment" /></td>
                                                 </tr>
                                                 <tr>
                                                      <td colspan="7"><html:submit styleClass="inputtext" onmousedown="javascript:saveComment();"><bean:message key="button.save"/></html:submit></td>
                                                 </tr>                                        
                                            </table>
                                       </p>
                                       </div>
                                       <div class="bottombig"></div>
                                  </div>
                             </div>
                             </logic:notPresent>
                             <logic:present name="savedcomment">
                             <div id="writeblogcomment">
                                  <div class="topbig">Comment saved<div class="headsmall">Kommentar gespeichert</div></div>
                                  <div id="bginhaltwriteblogcomment">
                                       <div class="breaker10" style="clear:left; "></div>
                                       <div align="center">
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                 <tr>
                                                      <td>Comment saved</td>
                                                 </tr>
                                            </table>
                                       </p>
                                       </div>
                                       <div class="bottombig"></div>
                                  </div>
                             </div>
                             </logic:present>
                             </div>
    </div>
    <html:hidden name="blogForm2" property="formaction"/><br>
    <html:hidden name="blogForm2" property="id"/><br>
    <% session.removeAttribute("savedcomment"); %>
    </html:form>
    </body>
    </html>

  • Controller Is Being Called Twice - Why???

    I think this is going to be a complicated question to answer but I'll try to explain what's going on as best I can. The basic problem I'm having is that the controller class gets called twice for some reason (instead of once) and I have no idea why. I type in a URL in my browser that goes to a JSP page called �myJsp.jsp�. Basically all that page contains is this...
    <tiles:insert definition =�my.tile� flush=�true�/>In my tiles-defs.xml file I have the following listing...<definition
    name="my.tile"
    path="SomeOtherJsp.jsp"
    controllerClass="x.y.z.MyController">
    </definition>
    x.y.z.MyController.java makes some calls to a DAO to retrieve data. MyController.java then puts that data into the requestScope for the JSP below to access...
    SomeOtherJsp.jsp has nothing special in it although it DOES contain a link to myJsp.jsp (and, somehow, it's like this link is being clicked even though I'm not clicking it).
    <a href="myJsp.jsp?someParam=<c:out value="${requestScope.someValue}"/>">Click Here To Do Something</a>If anyone can help I'd greatly appreciate it. By the way, I spoke to someone else who mentioned that I should turn this kind of thing into a struts action instead of doing a deletion within a controller class. I am going to refactor my code to do this. However, I'm still curious to know the answer to my question. Maybe it will help me get a better understanding of exactly what's going on in the world of servlets. :)

    Hi Shiv, <br><br>
    Yes I have placed System.out.println...and a debug point ...<br>
    super.processRequest(pageContext, webBean);<br>
    OAApplicationModule am = pageContext.getApplicationModule(webBean); <br>
    // String personId="13477";<br>
    // Serializable[] parameters = { personId };<br>
    if (!pageContext.isFormSubmission()) {     <br>
    am.invokeMethod("createEmployeeRow", null);<br>
    }<br>
    //am.invokeMethod("initDetails",parameters);<br>
    System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!IN Process Request"); <br>
    debug point is at String personID="13477"....<br><br>
    Thanks<br>Soujanya

  • Is this a Bug?: FocusListener called twice

    Hey all,
    Im having this problem since realease 1.4.2_04.
    Folks, try this code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FocusTest {
        public static void main(String[] args) {
            JFrame frame  = new JFrame("Focus test");
            final JTextField field1 = new JTextField("Test1");
            final JTextField field2 = new JTextField("Test2");
            field1.addFocusListener(new FocusAdapter(){
                public void focusGained(FocusEvent e){}
                public void focusLost(FocusEvent e){
                    if( !e.isTemporary() ){
                        System.out.println("ID: " + e.getID());
                        JOptionPane.showMessageDialog(null, "Focus lost in 1");
                        field1.requestFocus();
            frame.getContentPane().add(field1, BorderLayout.WEST);
            frame.getContentPane().add(field2, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setBounds(0,0,200,300);
            frame.show();
    } The problem is: when TF1 looses its focus, and is validated, then i force the focus to keep on TF1 by calling TF1.requestFocus(), somehow the event focusLsot is called twice for my TF.
    If i do not requestFocus() it work but I must force the focus on TF1.
    Im going nuts. Does anyonw apear to have this problems?? In old realeses, the same code work perfect. until 1.4.2 beta.
    Tks
    Bruno

    Hello all!
    I found out that somehow JDialog with requestfocus after, fires twice the lostFocus event. I dont know why. I opened a bug report so they can figure it out why is happaning.
    Tks folks!
    Bruno

  • Method CreateChildren in ApplicationControllBar class called twice after setting dock=true

    Hi during creating of a custom ApplicationControllBar
    component in ActionScript I probably found a (nasty) bug?!
    package net.neijman.julia.jaContainers
    import mx.containers.ApplicationControlBar;
    public class JAApplicationControlBar2 extends
    ApplicationControlBar
    public function JAApplicationControlBar2(): void
    this.dock = true;
    super();
    override protected function createChildren(): void
    trace("CREATECHILDREN EXECUTED");
    When I am using my simple custom component in my application:
    <jaContainer:JAApplicationControlBar2 />
    The trace message trace("CREATECHILDREN EXECUTED"); is
    executed twice (meaning CreateChildren is called twice BUT ONLY
    AFTER SETTING dock = true (see constructor). When setting dock =
    false CreateChildren is executed once. I want to build a framework
    on the standard components (depending heavily on the
    CreateChildren-method).
    In other words, creating dynamic components in the docked
    ApplicationControlBar in the method CreateChildren results in a
    double placement in the DisplayList.
    Has anyone has a clue what's going wrong here? (my
    workarround for now is to start the createChildren method with
    removeAllChildren();)
    Thanks Tom Neijman

    Interesting. I would file it as a bug here:
    http://bugs.adobe.com/jira/secure/Dashboard.jspa
    And then see what happens. If it's not a bug, you'll probably
    get a decent reason why this occurs in the bug notes.
    matt horn
    flex docs

  • ADF Faces: dialog framework calls  twice prepareModel and prepareRender

    Hi ,
    does anybody know why ADF Faces dialog framework calls twice prepareModel and prepareRender lifecycle methods . That's a really problem for me because i'm calling db procedures through backing beans methods which are attached on components properties.
    I cannot allow myself to cal the procedures more than once.
    Can somebody help me?
    Krasi

    Okay, although the servlet doesn't require to be run inside the JSF context, I added "/faces" to the URL simply because this would allow me to query the "postback" flag. In other words, I changed the invocation URL from "/jrrun" to "/faces/jrrun".
    In the servlet's "service()" method I put:
    logger.debug(">>>>>> isPostBack? " + AdfFacesContext.getCurrentInstance().isPostback());
    I also attached a JSF PhaseListener to the whole thing.
    Then I opened the parent page, I clicked on the button and the dialog appeared. The console output follows:
    07/01/19 21:37:05 ------------- start of phase RESTORE_VIEW 1
    07/01/19 21:37:05 ------------- end of phase RESTORE_VIEW 1
    07/01/19 21:37:05 ------------- start of phase RENDER_RESPONSE 6
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> RunJasperReport: beginning
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> isPostBack? false
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> RunJasperReport: repPath=/reports/newRegByBusType_Report.jasper
    2007-01-19 21:37:07,047 - DEBUG - >>>>>> RunJasperReport: report output (PDF) was generated successfully. Its total size is 59596 bytes.
    2007-01-19 21:37:07,047 - DEBUG - >>>>>> RunJasperReport: done
    07/01/19 21:37:07 ------------- end of phase RENDER_RESPONSE 6
    07/01/19 21:37:09 ------------- start of phase RESTORE_VIEW 1
    07/01/19 21:37:09 ------------- end of phase RESTORE_VIEW 1
    07/01/19 21:37:09 ------------- start of phase RENDER_RESPONSE 6
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> RunJasperReport: beginning
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> isPostBack? false
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> RunJasperReport: repPath=/reports/newRegByBusType_Report.jasper
    2007-01-19 21:37:09,672 - DEBUG - >>>>>> RunJasperReport: report output (PDF) was generated successfully. Its total size is 59596 bytes.
    2007-01-19 21:37:09,688 - DEBUG - >>>>>> RunJasperReport: done
    07/01/19 21:37:09 ------------- end of phase RENDER_RESPONSE 6
    By the way, partialSubmit="true" has the same effect as partialSubmit="false".
    I'm not sure I understand you correctly. Or perhaps you don't understand me correctly.
    I haven't got a problem with the parent page. I have a problem with the dialog page. It's executed twice. The RENDER_RESPONSE phase (as well as the RESTORE_VIEW phase) is executed twice.
    I want it to be executed only once. I don't want the servlet to be executed twice.
    Let me point out again that in the Embedded OC4J (inside JDeveloper) everything is okay. The servlet is executed only once. However, the same thing on OAS 10.1.3.1 runs twice.

  • Printing function gets called twice..!

    The following is my class that prints a string array which sometimes goes into multiple pages.. The code in which i create the multiple pages is below this class.. the problem is each time i append a new page to the book the print function in the class PaintC is called twice.. so if I write some additional code inside the print function to edit the strings .. it ends up running twice and the formatting i try to do gets messed up.. !! do you guys know why this is happening..? Please help.. ive been trying to find out since a very long time..!!
    The code in which i call this function is also shown below
    CLASS FOR PRINTING
    class PaintC
        implements Printable {
      String ad[];
      public PaintC(String ac[]) {
        System.out.println("Print Class Called 1");
        this.ad = ac;
      public int print(Graphics g, PageFormat pf, int pageIndex) throws
          PrinterException {
        System.out.println("Print Function Called 1");
        Graphics2D g2 = (Graphics2D) g;
        g.setFont(new java.awt.Font("Trebuchet MS", Font.PLAIN, 8));
        int xo = 60;
        int yo = 36;
        for (int y = 0; y < 76; y++) {
          try {
            g2.drawString(ad[y], xo, yo);
            yo += 9;
          catch (Exception r) {
            y = 76;
        return Printable.PAGE_EXISTS;
    CODE FOR CREATING MULTIPLE PAGES USING ABOVE CLASS
    void dotheprint() {
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat format = new PageFormat();
        Printable painter1;
        format = printerJob.defaultPage(format);
        Paper paper = format.getPaper();
        paper.setImageableArea(60, 36, 500, 756);
        format.setPaper(paper);
        // try storing in a string array each line
        Book bk = new Book();
        String ab = jTATRRep.getText();
        int i, j, lc = jTATRRep.getLineCount();
        String ac[] = new String[lc + 3];
        String ad[] = new String[78];
        ac = ab.split("\n");
        //System.out.println("Number of Lines = " + lc);
        //setting up pages as string arrays..
        // setting up first page
        //Assuming 76 lines per page
        for (i = 0; i < 76 && i < lc; i++) {
          try {
            ad[i] = ac;
    catch (Exception ex) {
    bk.append(new PaintC(ad), format);
    ad = null;
    // setting up second page if neccessary
    // //System.out.println("Number of Lines /76= "+lc/76);
    int pagec = lc / 76;
    int modul = lc % 76;
    int k;
    if (modul > 0) {
    pagec++;
    // //System.out.println("Number of pages : "+pagec);
    j = 76;
    while (pagec > 1) {
    ad = new String[76];
    k = 0;
    for (i = j; i < (lc - 1) && k < 76; i++) {
    // //System.out.println("ac[i]= "+ac[i]);
    ad[k] = ac[i];
    k++;
    bk.append(new PaintC(ad), format);
    ad = null;
    j += 76;
    pagec--;
    printerJob.setPageable(bk);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    System.out.println("Print Called 1");
    printerJob.print();
    System.out.println("Print Called 2");
    catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    CODE IN WHICH THE PRINT FUNCTION IS CALLED
    void jBPrint_actionPerformed(ActionEvent e) {
        dotheprint();
    class ContactManager_jBPrint_actionAdapter
        implements java.awt.event.ActionListener {
      ContactManager adaptee;
      ContactManager_jBPrint_actionAdapter(ContactManager adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jBPrint_actionPerformed(e);

    You might want to check out the [url http://forum.java.sun.com/thread.jsp?forum=57&thread=500687&tstart=0&trange=15]crosspost in the swing forum before spending your time answering this question.

  • Filters applied, called twice sometimes ...

    Hi,
    I have a small problem which give me headhache...
    I'm using a filter to make pre (authentification) and post processing (output the webpage using a XSL transformation).
    skeleton :
    ... doFilter ...
    //authentification
    chain.doFilter()
    //transformation and display
    When i'm aslink for a webpage (with a visitor account) there is no problem .., the webpage is displayed properly and the filter is called once ! perfect !
    but after my authentification (put a variable containing information onto the session with
    "sessionMgr.setSessionUser(session, user);") when I call the same webpage as before the webpage is displayed properly (that's a good point) but I saw in the tomcat console that after the end of the filter , the filter is called again with the same request or null sometimes .... GRRRRR
    I read John Hunter article about filters and in its clickstream exampl is using this tips :
    // Ensure that filter is only applied once per request.
    if (request.getAttribute(FILTER_APPLIED) == null) {
    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
    HttpSession session = ((HttpServletRequest)request).getSession();
    Clickstream stream = (Clickstream)session.getAttribute("clickstream");
    stream.addRequest(((HttpServletRequest)request));
    at the start of this filter ...
    can I have more explanation about this stuff ...
    I really don't understand why this happened ... it seems linked to the session management but I have no proof ...
    I find out hard to debug and hard to explain so
    THANKS A LOT FOR YOUR SUPPORT :)
    see ya
    Fran�ois (french guy so sorry for the english)

    hi there,
    well your problem is interesting........
    the solution that you have suggested in your problem regarding the use of FILTER_APPLIED, can be used but not as a long term solution.........
    well one thing i can tell you that as i was also facing the same problem of filter called twice, let me explain you the basic behaviour of the filter that a filter is called just before processing any request and again before giving response back to the particulare request........
    the next thing i can tell you is from your web.xml it is quite clear that you are mapping each request coming from dispatcher (your servlet) to your filter.......that means any request that points to dispatcher will go to the filter first and then to the actual servlet.
    one more thing you are loading the servlet on startup........
    just try to remove that code and then check..............
    because what happens in this case is when you start your application at that time your servlet will be loaded.........check whether the filter is called at that time or not......i think it must be called.......
    and when again a request will come the filter will be called..........this could be possible reasons your filter is called two times.........just try to delete the load on startup line from your web.xml for a while and then check..........
    regards
    Shishir

Maybe you are looking for