Printing DVT Components

So, I'm getting together some estimates for using a few dvt: components (pieGraph, horizontalBar graph, etc...) using 11.1.1.3 and was wondering if there is an easy way to make these graphs printable? I know that you can make them printable via firefox 3.6 by setting the imageFormat="PNG" but I would like to continue to use the default flash versions of the graphs if possible since they're the prettiest (yes, I know how shallow of me).
Is there a way to make these graphs printable without having to use the imageFormat="PNG" flag (or without having to add a "print this screen" button?
Thanks in advance,
-Rob

Flash doesn't print - so you'll have to convert them to PNG - if you prefer to have your graphs display in flash then the only option is to add a button to your page that uses the af:showPrintableBehavior tag to make the graph switch to png and print.

Similar Messages

  • How to print the components in scrollpane

    hi there,
    can anyone tell me how to print the scrollpane components, i mean the headers & the main view of the component. i've a scrollpane with the following code and i want to print the components:
    JScrollPane pane = new JScrollPane(aTextPane);
    pane.setRowHeaderView(aLineNumberComponent);my requirement is i've a editor & lineno component as textpanes and added to scrollpane & when asked to print it should print the lineno component which resides in scrollpane's row header & the editor textpane which is the main view in the scrollpane. how can i achieve this?
    i'd would appreciate any suggestions & codes given.
    thanx in advance.

    After adding/removing components to/from a panel try:
    panel.revalidate();
    panel.repaint() // sometimes this is also needed, I'm
    not sure whyI'm not certain, but I think that panel.revalidate() implicitly calls repaint() only if something actually changed in the layout. If nothing changed, it sees no reason to repaint; hence, if something changed in appearance but not in layout, you have to repaint it yourself.
    Or something like that. I'm no expert. ;)

  • Printing Swing components doesn't work on all printers? Please Help!

    I have a really serious problem. I try to print Swing components with the so called PrintUtilities class. The source code can be found here: http://archive.corewebprogramming.com/Chapter15/printing/PrintUtilities.java).
    My Swing components are panels (JPanel) including more panels and/or other components like text fields, text areas, combo boxes, radio buttons, check boxes and so on.
    On one of my printers (Kyocera mita FS 1010) it works fine. But on other printers (Panasonic DP-2000, HP Deskjet 890 C) the results are weird: Only the first component (independent of the component depth) is printed (and it is every time the same result!).
    I don't know whether this is important or not, but all printers I use are installed as network printers.
    I have already searched the forum but couldn't find a similar problem.
    Can anyone tell me what the problem is and what I can do to solve it?
    Thank you for any response in advance!

    try this:
    package ayto;
    import java.awt.*;
    import java.awt.print.*;
    import javax.swing.JComponent;
    public class ComponenteParaImprimir
    implements Printable {
    private Component mComponent;
    boolean isBook;
    final static boolean PARA_BOOK = true;
    final static boolean HARDCOPY = false;
    public ComponenteParaImprimir(Component c, boolean book) {
    mComponent = c;
    isBook = book;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0 && !isBook) {
    return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    boolean wasBuffered = disableDoubleBuffering(mComponent);
    mComponent.paint(g2);
    restoreDoubleBuffering(mComponent, wasBuffered);
    return PAGE_EXISTS;
    private boolean disableDoubleBuffering(Component c) {
    if (c instanceof JComponent == false) {
    return false;
    JComponent jc = (JComponent) c;
    boolean wasBuffered = jc.isDoubleBuffered();
    jc.setDoubleBuffered(false);
    return wasBuffered;
    private void restoreDoubleBuffering(Component c, boolean wasBuffered) {
    if (c instanceof JComponent) {
    ( (JComponent) c).setDoubleBuffered(wasBuffered);
    }

  • DVT Components with ADS

    Is there any documentation or example on how to use Active data service with DVT Components
    Regards

    Hi,
    none that I am aware of yet.
    Frank

  • Problem with DVT components on headless server

    JDEV/ADF VERSION: 11.1.1.0.1
    TECHNOLOGY: Fusion Web Application, WLS 10.3
    Hi,
    maybe someone has/has the same problem. I have created a page with
    some basic dvt components like pie and bar charts. Everything works fine on my dev machine.
    When I deploy the generated EAR on the test env (OEL 5, headless) and try to access the
    page (which contains the dvt components) I get the following exception:
    "Can't connect to x11 server ...."
    and the WLS shuts down!!!!
    Has anyone an idea if an x server is mandatory?
    Thanks in advance for any hints,
    Andreas.

    Andreas,
    I don't have a Linux box to test with at the moment, but it has been a common thing I've dealt with in other environments. Have you tried setting up a VNC server on the Linux box and setting the DISPLAY environment variable to reference that display before starting WLS?
    John

  • Print 2D components via printer

    hi,
    Printer is connected to windows machine - samba running on it
    Client machines are running with SuSE linux.
    Client machine configured the printer via SMB access.
    Through this configuration we can print documents from open office and editors.. its running fine
    Now we want to print documents via java program. using doc favour we suceesfully done it.
    Now we need to print pre printed statements thru java program. So using swing components we positioned it and sent print request from linux .. but it is not printing. When the same program run in a windows machine then it is printing. How this can be eliminated...
    Can anybody please help me how can this be resolved

    It appears the product you have is a commerical LaserJet.
    I recommend posting in the commercial LaserJet forums.
    ↙-----------How do I give Kudos?| How do I mark a post as Solved? ----------------↓

  • How do we print multiple components each in a different page?

    hello
    I would like to print multiple JPanels (lets say an array) each in a different page.
    The question I ask is about the following code
             printerJob.setPrintable(printTable.getInstance(), pageFormat);
                  try
                        if (printerJob.printDialog())
                             printerJob.print();
                        }

    Lets say that we have the following code. How do we modify it?
    * This example is from the book "Java Foundation Classes in a Nutshell".
    * Written by David Flanagan. Copyright (c) 1999 by O'Reilly & Associates. 
    * You may distribute this source code for non-commercial purposes only.
    * You may study, modify, and use this example for any purpose, as long as
    * this notice is retained.  Note that this example is provided "as is",
    * WITHOUT WARRANTY of any kind either expressed or implied.
    import java.awt.*;
    import java.awt.print.*;
    import java.io.*;
    import java.util.Vector;
    public class PageableText implements Pageable, Printable {
      // Constants for font name, size, style and line spacing
      public static String FONTFAMILY = "Monospaced";
      public static int FONTSIZE = 10;
      public static int FONTSTYLE = Font.PLAIN;
      public static float LINESPACEFACTOR = 1.1f;
      PageFormat format;   // The page size, margins, and orientation
      Vector lines;        // The text to be printed, broken into lines
      Font font;           // The font to print with
      int linespacing;     // How much space between lines
      int linesPerPage;    // How many lines fit on a page
      int numPages;        // How many pages required to print all lines
      int baseline = -1;   // The baseline position of the font.
      /** Create a PageableText object for a string of text */
      public PageableText(String text, PageFormat format) throws IOException {
        this(new StringReader(text), format);
      /** Create a PageableText object for a file of text */
      public PageableText(File file, PageFormat format) throws IOException {
        this(new FileReader(file), format);
      /** Create a PageableText object for a stream of text */
      public PageableText(Reader stream, PageFormat format) throws IOException {
        this.format = format;
        // First, read all the text, breaking it into lines.
        // This code ignores tabs, and does not wrap long lines.
        BufferedReader in = new BufferedReader(stream);
        lines = new Vector();
        String line;
        while((line = in.readLine()) != null)
          lines.addElement(line);
        // Create the font we will use, and compute spacing between lines
        font = new Font(FONTFAMILY, FONTSTYLE, FONTSIZE);
        linespacing = (int) (FONTSIZE * LINESPACEFACTOR);
        // Figure out how many lines per page, and how many pages
        linesPerPage = (int)Math.floor(format.getImageableHeight()/linespacing);
        numPages = (lines.size()-1)/linesPerPage + 1;
      // These are the methods of the Pageable interface.
      // Note that the getPrintable() method returns this object, which means
      // that this class must also implement the Printable interface.
      public int getNumberOfPages() { return numPages; }
      public PageFormat getPageFormat(int pagenum) { return format; }
      public Printable getPrintable(int pagenum) { return this; }
       * This is the print() method of the Printable interface.
       * It does most of the printing work.
      public int print(Graphics g, PageFormat format, int pagenum) {
        // Tell the PrinterJob if the page number is not a legal one.
        if ((pagenum < 0) | (pagenum >= numPages))
          return NO_SUCH_PAGE;
        // First time we're called, figure out the baseline for our font.
        // We couldn't do this earlier because we needed a Graphics object
        if (baseline == -1) {
          FontMetrics fm = g.getFontMetrics(font);
          baseline = fm.getAscent();
        // Clear the background to white.  This shouldn't be necessary, but is
        // required on some systems to workaround an implementation bug
        g.setColor(Color.white);
        g.fillRect((int)format.getImageableX(), (int)format.getImageableY(),
                   (int)format.getImageableWidth(),
                   (int)format.getImageableHeight());
        // Set the font and the color we will be drawing with.
        // Note that you cannot assume that black is the default color!
        g.setFont(font);
        g.setColor(Color.black);
        // Figure out which lines of text we will print on this page
        int startLine = pagenum * linesPerPage;
        int endLine = startLine + linesPerPage - 1;
        if (endLine >= lines.size())
          endLine = lines.size()-1;
        // Compute the position on the page of the first line.
        int x0 = (int) format.getImageableX();
        int y0 = (int) format.getImageableY() + baseline;
        // Loop through the lines, drawing them all to the page.
        for(int i=startLine; i <= endLine; i++) {
          // Get the line
          String line = (String)lines.elementAt(i);
          // Draw the line.
          // We use the integer version of drawString(), not the Java 2D
          // version that uses floating-point coordinates. A bug in early
          // Java2 implementations prevents the Java 2D version from working.
          if (line.length() > 0)
            g.drawString(line, x0, y0);
          // Move down the page for the next line.
          y0 += linespacing; 
        // Tell the PrinterJob that we successfully printed the page.
        return PAGE_EXISTS;
       * This is a test program that demonstrates the use of PageableText
      public static void main(String[] args) throws IOException, PrinterException {
        // Get the PrinterJob object that coordinates everything
        PrinterJob job = PrinterJob.getPrinterJob();
        // Get the default page format, then ask the user to customize it.
        PageFormat format = job.pageDialog(job.defaultPage());
        // Create PageableText object, and tell the PrinterJob about it
        job.setPageable(new PageableText(new File("file.txt"), format));
        // Ask the user to select a printer, etc., and if not canceled, print!
        if (job.printDialog())
             job.print();
    }thank you in advance

  • How can I Print a JPanel including all added Components?

    Hello dear saviours,
    I have a JPanel object which is responsible for displaying a Graph.
    I need to Print the Components of this JPanel as close to what they look like to the user as possible.
    I thought about casting the JPanel into an Image of some kind, but couldn't find anything but how to add am Image to a JPanel (God damned search engines :-).
    But wait, this gets more interesting!
    I need to have control over the scale of the Printed matterial.
    I want the option to choose between a single page and dividing the drawing the JPanel displays into Multiple-Pages.
    In both cases I need full details of all the data (Nodes, Arcs, Text describing the various Nodes and Arcs names or type, etc.).Keeping the sizes of all these components is also important (that means, I don't want the nodes to be tinny-winny and the Fonts to be twice as large as the nodes and so on...).
    Attached is the code of the PrintUtillity class I created as an API for printing the JPanel data:
    package ild;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    * an arbitrary component. Just pass the component to the
    * PrintUtilities.printComponent. The component you want to
    * print doesn't need a print method and doesn't have to
    * implement any interface or do anything special at all.
    * <P>
    * If you are going to be printing many times, it is marginally more
    * efficient to first do the following:
    * <PRE>
    * PrintUtilities printHelper = new PrintUtilities(theComponent);
    * </PRE>
    * then later do printHelper.print(). But this is a very tiny
    * difference, so in most cases just do the simpler
    * PrintUtilities.printComponent(componentToBePrinted).
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    // double scale = 2;
    // g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    double scaleFactor = java.lang.Math.min((double)this.componentToBePrinted.getSize().width/(double)(pageFormat.getImageableWidth()),
    (double)this.componentToBePrinted.getSize().height/(double)(pageFormat.getImageableHeight()));
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.scale(1.0/scaleFactor,1.0/scaleFactor);
    // disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

    That's a nice utility, but my JPanel gets truncated when printed. Is there a way to print a JPanel in full.

  • How to print a dialog box with all its components ?

    Hi !
    I've written an application.It has a dialog box [JDialog] containing following components:
    1) 2 JLabels.
    1) A JTextField.
    3) A JTable with some values.
    4) A JProgressBar.
    5) A JButton.
    6) An animated gif image.
    I want to print the dialog box with all its components exactly as the are [ Except the button & animated gif ].
    Would anybody please help me?
    My Operating System: Windows XP

    The article over at http://java.sun.com/developer/technicalArticles/Printing/Java2DPrinting/ has some helpful information on printing Swing components.
    It suggests creating a subclass of the JComponent that you want to print, and have it implement Printable interface.
    So, something like (note, uncompiled / untested code alert) :
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.HeadlessException;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import javax.swing.JDialog;
    public class PrintableDialog extends JDialog implements Printable {
          * Or whichever constructor you need...
         public PrintableDialog(Frame owner, String title, boolean modal) throws HeadlessException {
              super(owner, title, modal);
          * Implementation of the Printable interface.
           public int print(Graphics g, PageFormat pf, int pageIndex) {
              if (pageIndex != 0) return NO_SUCH_PAGE;
              Graphics2D g2 = (Graphics2D) g;
              g2.translate(pf.getImageableX(), pf.getImageableY());
              getContentPane().paint(g2);
              return PAGE_EXISTS;
    }Cheers,
    John

  • Problem Printing Documents - No Doc Flavors Supported

    Hello everybody. I've been trying to implement a print feature in my applications and I've had absolutely zero luck. Basically, I'm trying to print the contents of an html file. However, there are no PrintServices that show up on my machine that support DocFlavors text/html, or even text/plain.
    I searched all over the Internet, but the only tutorials I found involved printing GUI components. I tried putting everything in a JEditorPane and then printing it, but the table is so large horizontally, it runs off the side, so I don't think that route will work.
    I checked IRC, scanned through all of Sun's tutorials and print service API documentation, and even searched around for open source Java word processors so I could check how their print features are implemented, but I can't find anything to help me figure this out. I know there has to be a way, though... or stuff like EIOffice and ThinkFree.com wouldn't be able to work. Can somebody please point me in the right direction?
    Here's the current code I have:
              //display print dialog
              DocFlavor df=new DocFlavor("text/html; charset="+DocFlavor.hostEncoding,"java.io.InputStream");
              PrintRequestAttributeSet attributes=new HashPrintRequestAttributeSet();
              attributes.add(new javax.print.attribute.standard.JobName("NutraSmart Menu",null));
              PrintService[] services=PrintServiceLookup.lookupPrintServices(df,attributes);
              PrintService service=null;
              if(services.length>0)
                   service=ServiceUI.printDialog(this.getGraphicsConfiguration(), this.getX()+50, this.getY()+50, services, services[0], null, attributes);
              else
                   JOptionPane.showMessageDialog(getContentPane(),"No print services could be found to print this menu.","Error printing menu",JOptionPane.ERROR_MESSAGE);
                   nutrasmart.debug(nutrasmart.ERROR,"Could not find any services to print menu");
              //print menu
              if(service!=null)
                   try
                        //create temporary HTML file to print from
                        File tmpfile=File.createTempFile("nsmenu",".html");
                        tmpfile.deleteOnExit();
                        String tmpfilestr=tmpfile.getPath();
                        export_HTML(tmpfilestr);
                        FileInputStream tmpfilestream;
                        try
                             tmpfilestream=new FileInputStream(tmpfilestr);
                        catch(FileNotFoundException e)
                             JOptionPane.showMessageDialog(getContentPane(),"A problem was encountered while preparing the menu to print.","Error printing menu",JOptionPane.ERROR_MESSAGE);
                             return;
                        //print document
                        DocPrintJob pj=service.createPrintJob();
                        Doc doc=new SimpleDoc(tmpfilestream,df,new HashDocAttributeSet());
                        pj.print(doc,attributes);
                   catch(Exception e)
                        JOptionPane.showMessageDialog(getContentPane(),"There was a problem with printing the menu.","Error printing menu",JOptionPane.ERROR_MESSAGE);
                        nutrasmart.debug(nutrasmart.ERROR,"Error printing file",e.getMessage());
              }

    Really we have a crazy font management.
    We have more than 9000 fonts in the /Library/Fonts
    To avoid conficts between the the installed system fonts and the Document font folder, we don't use the document font folder, so that we use always the /Library/Fonts/ fonts installed. Anyway some time ago we also used the Document Font folder and we got the same problem.
    I think that your idea about closing the document before the printing process has been finished is very interesting. What I do is :
    doc.print(print_preset);
    doc.close();
    But I don't how can I test if the document is being closed before finishing the printing process.
    Regards

  • Oracle/adf/view/rich/model/AsyncFetch Error in DVT

    Experts,
    We have some DVT components in our application which runs perfectly on integrated local Weblogic Sever. Once we deploy it to a Weblogic Standalone server, we are getttnig the following error while trying to access the DVT graph page. Rest of the application is working properly.
    Error : oracle/adf/view/rich/model/AsyncFetch
    followed by ADF Faces 60097
    Jdev 11.1.1.5 and WLS 10.3.5
    thnks

    Solution : Go to EAR Deployment Profile Properties -> File Groups -> Application Libraries ->Filters and here you have to remove the libraries that are ADF DVT.

  • Trying to pick up the printer

    I have an example below using a simple gui that has print function in it. The aim of the program is when the user clicks on the print button that they can call p the print and print waht ever is in the text area. I'm not sure if i'm in the right forum now so bear with me.
    If any one has any ideas or knows how to fix it theres one error in total on the tool kit, its fairly well commented now so hope fully some one can see the problem is fairly annoying
    Help wold ge great thanking you
    Ambrose
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.PrintJob;
    import java.util.List;
    //import sun.tools.javac.Main;
    public class print extends JPanel {
        private JButton jButton14;
        private JTextArea jTextArea1;
        public print() {
            //construct components
            jButton14 = new JButton ("print");
            jTextArea1 = new JTextArea (5, 5);
            //adjust size and set layout
            setPreferredSize (new Dimension (496, 371));
            setLayout (null);
            //add components
            add (jButton14);
            add (jTextArea1);
            //set component bounds (only needed by Absolute Positioning)
            jButton14.setBounds (210, 245, 100, 20);
            jTextArea1.setBounds (25, 55, 435, 160);
         public void jButton14_actionPerformed(ActionEvent e)
              printText(jTextArea1.getText());
    // Draw individual lines from the text onto pages of a new print job
        private void printText(String text)
            PrintJob p = getToolkit().getPrintJob(this, "Print Job", null); // This causes the print dialog box to pop up
            int pageLength = p.getPageDimension().height; // Find out page size
            StringTokenizer theText = // Prepare to break up the text into lines (one line = one token)
                new StringTokenizer(text, "\n", true); // Returns \n tokens too
            Graphics g = null;
            int lineInc = 0;
            int initialYForPage = 0; // y coord of top line on page
            int yMax = pageLength - 100; // y coord of bottom line, allowing for borders of 50 top and bottom
            int x = 0;                // Initial print position
            int y = initialYForPage;
            int pageNumber = 0;
            boolean newPage = true; // To force page layout initialization
            while (theText.hasMoreTokens()) {           // Scan the lines in theText
                if (newPage) { // Start of a page?
                    g = nextPage(p); // Yes, set up new page
                    lineInc = g.getFontMetrics().getHeight(); // The line height in pixels for the current font
                   y = initialYForPage;
                   pageNumber++;
                    g.drawString("Page " + pageNumber, x, y);      // Page number at top
                    y += 2 * lineInc;           // Space for a blank line
                    newPage = false;
                String nextBit = theText.nextToken(); // Get next line or \n if it's an empty line
                if (nextBit.equals("\n")) // End of an empty line?
                    nextBit = ""; // Yes, prepare to output an empty line
                else // No, we got a line
                if (theText.hasMoreTokens()) { // \n following?
              String discard = theText.nextToken(); // Yes, discard the \n following the line
                // System.out.println(nextBit);       // Just to check, during testing
                g.drawString(nextBit, x, y);      // Draw next line
                y += lineInc;     // and move down a bit (x doesn't change: always draw at left)
                if (y > yMax) {      // At end of page?
                    g.dispose();           // Yes, print it
                    newPage = true;      // Force page initialization if there's another page
            if (!newPage)
                g.dispose(); // Print last page, if not already done
            p.end(); // End of print job - phew!
        } // printText
        // Grab a new page for printing on
        private Graphics nextPage(PrintJob p) {
            Graphics g = p.getGraphics();
            g.translate(50, 50); // To move image away from top left of page
            g.setFont(new Font("SansSerif", Font.PLAIN, 10));
            return g;
        } // nextPage
        public static void main (String[] args) {
            JFrame frame = new JFrame ("print");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add (new print());
            frame.pack();
            frame.setVisible (true);
    }

    Sorry the problem was in this line of code it picks up the gettoolkit as an error and when i excute the frame nothing happens
    PrintJob p = getToolkit().getPrintJob(this, "Print Job", null);

  • ADS query for DVT

    Hi
    I am building a ActiveDataModel for the DVT components. However, I am not sure on how to fire insert/ update events to ADS for DataModel(graphs etc) objects. Could some one point me to documentation / samples that demonstrate this
    Specifically
    1. I have a DVT based off a java DC.
    2. I have a Mgd Bean that implements ActiveDataModelDecorator, this returns the DVT in step1 for getModel() and a custom implementation for ActiveDataModel
    3. I want to know how to fire active data events(update/insert/delete) to the DVT using the customactivedatamodel above.
    4. How do I find out the row key for my iterator if I use the same DC for a table/tree table
    Thanks
    Ravi

    Thanks all for the response. However,I still cannot find
    1. How to properly construct an event using the ADSEventUtil that has a bunch of object[] and string[] parameters and a key path that I am not sure how to derive from a java data control.
    2. Also, in my case the DVT is bound to a Java DC. so, would firing an event result is getDataModel call so that it returns the updated model ?

  • Problems displaying deserialized components

    I'm trying to save the state of some objects which extend JComponent and JLayeredPane, and they don't all redisplay on deserializing, although they seem to be in the containment tree.
    Basically, I have a class GamePanel which extends JLayeredPane. Also classes Square and Region both of which extend JComponent and use 2D graphics for painting themselves. It seems to serialize OK (but how does one tell?). But when I deserialize, only the lower level of the GamePanel is painted. However, the higher level is populated.
    Does anyone have any idea why they're not displaying? The code is below (TestKiller and its menus are generated by NetBeans - hence the slightly odd code). There are 5 menu items (I've simplified a lot from the original so it's a bit clunky): Add Region (you can only do this once in this version), Save As which serializes to a file, Restore which deserializes from a file, Exit which is obvious and Print which outputs the containment hierarchy of GamePanel to standard output.
    If you want to try it out, fire up the program, do a File|Add to add a Region (see the dotted lines) and File|Print to see that there's a Square at level 2 and a Region at level 3. Then File|Save as... to save it. Quit the program.
    Fire it up again and do a File|Restore and a File|Print. You'll see from the output that the Square and Region are there with identical parameters to the output before, but the Region hasn't displayed its outline.
    The output's below, with java-like comments added to show what I've done:
    D:>java -jar test*
    Painting gridlayer
    // File|Add Region
    New region 1
    Selecting square
    Checking region 1
    Painting gridlayer
    Painting region 1
    //File|Print
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    \\File|Save
    Saving game to bug1.ksd
    D:>java -jar test*
    Painting gridlayer
    \\File|Restore
    Restoring game bug1.ksd
    Restored
    \\File|Print - same as above but only Square is displayed
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    D:>
    Please someone tell me what I'm doing wrong. As a serialization newbie it's probably something simple, but no amount of validate() and pack() makes any difference.
    The code's below - a bit long I'm afraid but it's difficult to cut it down much more and display the problem. The main class (TestKiller) was generated by NetBeans.
    * TestKiller.java
    * Created on 01 August 2006, 22:13
    package com.ptoye.TestSBug1;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    * @author  PToye
    public class TestKiller extends javax.swing.JFrame {
      private GamePanel p;
      final String fileExtension="ksd";
       * Creates new form TestKiller
      public TestKiller() {
        initComponents();
        p=new GamePanel();
        setContentPane(p);
        p.setOpaque(true);
        setSize(p.getPreferredSize());
        pack();
      public static void showMessage(String s) {
        JOptionPane.showMessageDialog(null,s,"Error",JOptionPane.ERROR_MESSAGE);
      /** This method is called from within the constructor to
       * initialize the form.
       * WARNING: Do NOT modify this code. The content of this method is
       * always regenerated by the Form Editor.
      private void initComponents() {                         
        jMenuBar1 = new javax.swing.JMenuBar();
        jmFile = new javax.swing.JMenu();
        jmiAddRegion = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jmiSaveAs = new javax.swing.JMenuItem();
        jmiRestore = new javax.swing.JMenuItem();
        jmiExit = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jmiPrint = new javax.swing.JMenuItem();
        FormListener formListener = new FormListener();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Restore bug");
        jmFile.setText("File");
        jmiAddRegion.setText("Add region");
        jmiAddRegion.addActionListener(formListener);
        jmFile.add(jmiAddRegion);
        jmFile.add(jSeparator2);
        jmiSaveAs.setMnemonic('s');
        jmiSaveAs.setText("Save as...");
        jmiSaveAs.addActionListener(formListener);
        jmFile.add(jmiSaveAs);
        jmiRestore.setMnemonic('r');
        jmiRestore.setText("Restore");
        jmiRestore.addActionListener(formListener);
        jmFile.add(jmiRestore);
        jmiExit.setMnemonic('x');
        jmiExit.setText("Exit");
        jmiExit.addActionListener(formListener);
        jmFile.add(jmiExit);
        jmFile.add(jSeparator1);
        jmiPrint.setText("Print");
        jmiPrint.addActionListener(formListener);
        jmFile.add(jmiPrint);
        jMenuBar1.add(jmFile);
        setJMenuBar(jMenuBar1);
        pack();
      // Code for dispatching events from components to event handlers.
      private class FormListener implements java.awt.event.ActionListener {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          if (evt.getSource() == jmiSaveAs) {
            TestKiller.this.jmiSaveAsActionPerformed(evt);
          else if (evt.getSource() == jmiRestore) {
            TestKiller.this.jmiRestoreActionPerformed(evt);
          else if (evt.getSource() == jmiExit) {
            TestKiller.this.jmiExitActionPerformed(evt);
          else if (evt.getSource() == jmiPrint) {
            TestKiller.this.jmiPrintActionPerformed(evt);
          else if (evt.getSource() == jmiAddRegion) {
            TestKiller.this.jmiAddRegionActionPerformed(evt);
      private void jmiAddRegionActionPerformed(java.awt.event.ActionEvent evt) {                                            
        p.dummyAdd();
        jmiAddRegion.setEnabled(false);
      private void jmiPrintActionPerformed(java.awt.event.ActionEvent evt) {                                        
        p.print();
      private void jmiSaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                         
        File f;
        ObjectOutputStream oos=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter(new KDSFileFilter());
        jfc.showSaveDialog(this);
        f=jfc.getSelectedFile();
        if (f==null) {
          showMessage("Null file found");
        int i=f.getName().lastIndexOf(".");
        if (i==-1) {
          f=new File(f.getAbsolutePath()+"."+fileExtension);
        try {
          oos=new ObjectOutputStream(new FileOutputStream(f));
        } catch (FileNotFoundException ex) {
          showMessage("Cannot find file "+f.getName());
          return;
        } catch (IOException ex) {
          showMessage("Cannot open file "+f.getName());
          return;
        if (oos!=null) {
          System.out.println("Saving game to "+f.getName());
          try {
            oos.writeObject(p);
          } catch (IOException ex) {
            showMessage("Cannot write game to "+f.getName()+"\n"+ex.getMessage());
          } finally {
            try {
              oos.close();
            } catch (IOException ex) {
      private void jmiExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        System.exit(0);
      private void jmiRestoreActionPerformed(java.awt.event.ActionEvent evt) {                                          
        File f;
        ObjectInputStream ois=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter( new KDSFileFilter());
        jfc.showOpenDialog(this);
        f=jfc.getSelectedFile();
        if (f!=null) {
          try {
            ois=new ObjectInputStream(new FileInputStream(f));
          } catch (FileNotFoundException ex) {
            showMessage("Cannot find file "+f.getName());
            return;
          } catch (IOException ex) {
            showMessage("Cannot open file "+f.getName());
            return;
          if (ois!=null) {
            System.out.println("Restoring game "+f.getName());
            try {
              p=(GamePanel) ois.readObject();
            } catch (IOException ex) {
              showMessage("Cannot read game from file "+f.getName());
            } catch (ClassNotFoundException ex) {
              showMessage("Cannot restore game - wrong object type");
            try {
              ois.close();
            } catch (IOException ex) {
            pack();
            p.validate();
            p.repaint();
            System.out.println("Restored");
      private class KDSFileFilter extends javax.swing.filechooser.FileFilter {
        public boolean accept(File f) {
          if (f.isDirectory()) {
            return true;
          String ext = null;
          String s = f.getName();
          int i = s.lastIndexOf('.');
          if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
          return (ext==null || ext.equalsIgnoreCase(fileExtension));
        public String getDescription() {
          return "Killer Su Doku games";
       * @param args the command line arguments
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TestKiller().setVisible(true);
      // Variables declaration - do not modify                    
      private javax.swing.JMenuBar jMenuBar1;
      private javax.swing.JSeparator jSeparator1;
      private javax.swing.JSeparator jSeparator2;
      private javax.swing.JMenu jmFile;
      private javax.swing.JMenuItem jmiAddRegion;
      private javax.swing.JMenuItem jmiExit;
      private javax.swing.JMenuItem jmiPrint;
      private javax.swing.JMenuItem jmiRestore;
      private javax.swing.JMenuItem jmiSaveAs;
      // End of variables declaration                  
    * GamePanel.java
    * Created on 10 January 2007, 18:45
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.JLayeredPane;
    * @author PToye
    public class GamePanel extends JLayeredPane implements Serializable {
      private static final int GRID_LEVEL=2;
      private static final int REGIONS_LEVEL=3;
      private static final int THICK_WIDTH=4;
      private static final int THIN_WIDTH=1;
      static final int SQUARE_SIZE=60;
      private static final int SQUARES=1;  // test size
      static final int BIGSQUARES=SQUARES*SQUARES;
      static final int TotalSize=(SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
          BIGSQUARES*SQUARE_SIZE;
      public final Color NORMAL_BACK_COLOUR=Color.WHITE;
      public final Color SELECTED_BACK_COLOUR=Color.PINK;
      int coordArray;  // used to be an array of start coords of each square
      private Region newRegion;
      private int regionId=1;
      private Square squareArray; // used to be an array
      private Region regions; // used to be a set
      /** Creates a new instance of GamePanel */
      public GamePanel() {
        super();
        regions=null;
        makeGridLayer();  //adds the white square
        setPreferredSize(new Dimension(TotalSize,TotalSize));
        setVisible(true);
        newRegion=null;
        setFocusable(true);
      public void dummyAdd() {
        setupRegion(squareArray);
        if (newRegion.checkNewRegion(1)) {
          addRegion(newRegion);
      public void addRegion(Region r) {
        if (regions==null) {
          regions=r;
          add(r,new Integer(REGIONS_LEVEL));
          r.repaint();
      void print() {
        Component[] cList=getComponents();
        System.out.println("Printing Gamepanel components");
        for (int i = 0; i < cList.length; i++) {
          Component c=cList;
    System.out.println(c.toString());
    System.out.println(" Bounds "+c.getBounds());
    System.out.println(" Layer "+getLayer(c));
    if (c instanceof Container) {
    printContainer((Container)c," ");
    void printContainer(Container c, String preString) {
    Component[] cList1=c.getComponents();
    for (int i = 0; i < cList1.length; i++) {
    Component comp=cList1[i];
    System.out.println(preString+comp.toString());
    System.out.println(preString+" Bounds "+comp.getBounds());
    if (comp instanceof Container) {
    printContainer((Container)comp,preString+" ");
    private void setupRegion(Square s) {
    if (newRegion==null) {
    newRegion=new Region(regionId++,this);
    Region r=s.getRegion();
    if (r==null) {
    newRegion.addSquare(s);
    selectSquare(s);
    s.setRegion(newRegion);
    } else {
    System.exit(1); // should not happen
    private void makeGridLayer() {
    int currentXCoord;
    int currentYCoord;
    int arrayIndex=0;
    Square sq;
    currentXCoord=THICK_WIDTH;
    currentYCoord=THICK_WIDTH;
    coordArray=currentYCoord;
    sq=new Square(0,0, NORMAL_BACK_COLOUR,this);
    add(sq,new Integer(GRID_LEVEL));
    squareArray=sq;
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    System.out.println("Painting gridlayer");
    g2.setBackground(Color.BLACK);
    g2.setColor(Color.BLACK);
    g2.fillRect(0,0,TotalSize,TotalSize);
    void selectSquare(Square s) {
    System.out.println("Selecting square");
    s.setBackColour(SELECTED_BACK_COLOUR);
    * Square.java
    * Created on 28 December 2006, 15:53
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import javax.swing.JComponent;
    * @author PToye
    class Square extends JComponent implements Serializable {
    * X index in grid
    private int xIndex;
    * Y index in grid
    private int yIndex;
    * The square's parent grid
    private GamePanel parent;
    * Region it belongs to (or null if none)
    private Region region;
    * The background colour
    private Color backColour;
    private boolean marked;
    // public Square() {
    // System.out.println("New Square - null constructor");
    // addMouseListener(parent);
    * Create a new square
    public Square(int x, int y, Color bcol, GamePanel parent) {
    this.parent=parent;
    xIndex=x;
    yIndex=y;
    backColour=bcol;
    region=null;
    setName("Square-"+x+":"+y);
    setBounds(parent.coordArray,parent.coordArray,
    GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    setOpaque(true);
    setVisible(true);
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    // System.out.println("Painting square "+xIndex+","+yIndex+":"+getBounds());
    g2.setColor(backColour);
    g2.fillRect(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    g2.setColor(Color.BLACK);
    public Dimension getPreferredSize() {
    return new Dimension(GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public void setBackColour(Color backColour) {
    this.backColour = backColour;
    repaint(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public Region getRegion() {
    return region;
    public void setRegion(Region region) {
    this.region = region;
    * Region.java
    * Created on 28 December 2006, 15:59
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.GeneralPath;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JComponent;
    * @author PToye
    * Class representing a region whose total sum is known
    public class Region extends JComponent implements Serializable {
    private static final float BORDER_WIDTH=1f;
    private static final float DASH_LENGTH=4f;
    private static final float[] dashes={DASH_LENGTH,DASH_LENGTH};
    private static final BasicStroke borderStroke=
    new BasicStroke(BORDER_WIDTH,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,
    1f,dashes,0);
    private static final int borderInset=3;
    private GamePanel parent;
    * The sum as given
    private int total;
    private String totalString;
    private int id;
    * The squares constituting the region
    private Square contents; // the square in the region
    private Square leadSquare; // top left-hand square
    private int leadXCoord,leadYCoord; // X, Y coords of lead square wrt border
    private GeneralPath border=null;
    public Region(int id, GamePanel parent) {
    super();
    this.id=id;
    this.parent=parent;
    setName("Region-"+id);
    contents=null;
    border=new GeneralPath();
    System.out.println("New region "+id);
    public void addSquare(Square s) {
    if (contents!=null) {
    contents=s;
    public boolean checkNewRegion(int tot) {
    System.out.println("Checking region "+id);
    border.moveTo(borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,borderInset);
    setBounds(parent.coordArray,parent.coordArray,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    repaint();
    return true;
    public void paintComponent(Graphics g) {
    int newX, newY;
    System.out.println("Painting region "+id);
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    g2.setColor(Color.BLACK);
    g2.setStroke(borderStroke);
    g2.draw(border);

    OK, I asked the FTE team and got this reply: "Lucida Grande is CTS's fallback font for Thai.  This font on OS 10.7 and 10.6 are not supporting Thai anymore.  The version on 10.5 was supporting it." This means that it's our bug that we keep using Lucida Grande as fallback font even Apple dropped support Thai script with that font after 10.6. Unfortunately this bug was deferred from current development release (11.2) because of time constraint. If this support is critical for your business, can you open a bug in our public bugbase and ask as many vote as possible? In this way I may be able to convince internal team to fix this bug in next release.
    Thank you for your feedback!
    Hitomi

  • Navigation to a page from Pie Chart (or DVT component) on mouse click

    ADF Mobile: I have a pie chart on page_1. How to open a new page (page_2) when a slice of the pie chart is clicked in ADF Mobile?
    Edited by: 969936 on Jan 24, 2013 9:17 PM
    Edited by: Jugal Madhavan on Jan 25, 2013 9:21 PM

    Thank you Mr. Frank for your reply.
    I am using JDev11gR2 (Studio Edition Version 11.1.2.3.0 Build JDEVADF_11.1.2.3.0_GENERIC_120914.0223.6276.1) to create a Mobile Application (ADF).
    Here, i dont have "Action" property for any DVT Components.
    But if we are creating a web application, "ClickAction" property is available for DVT components which can be used to perform some action.
    Kindly request you to share further inputs.

Maybe you are looking for