JComponent needs to be painted on creation

I have a Card class that extends JComponent. The paintComponent method is implemented. Added it to a JPanel. Added the JPanel to the JFrame. The JComponent only shows up when the frame is resized, not when the frame is first shown on screen. The only fix I can think of is to place a method in the constructor of JComponent that paints itself on creation. Has anyone had this problem before?
public Card(Rank rank, Suit suit, String img) {
        super();
        this.rank = rank;
        this.suit = suit;
        this.image = Toolkit.getDefaultToolkit().createImage(img);
     setPreferredSize(new Dimension(400, 300));
     setVisible(true);
public void paintComponent(Graphics g) {
boolean x = g.drawImage(this.image, getX(), getY(), null);
}

If I'm not mistaken, the Toolkit#createImage() methods do asynchronous loading of the image, so when your JFrame is being displayed, the image hasn't been fully loaded yet. Use a method of loading the image that blocks until it's complete, such as ImageIO. Here's a working example:
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageJPanelTest extends JFrame {
     public ImageJPanelTest() {
          JPanel contentPane = new Card();
          setContentPane(contentPane);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setTitle("Image JPanel Test");
          pack();
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    new ImageJPanelTest().setVisible(true);
     class Card extends JPanel {
          private Image image;
          public Card() {
               String img = "anchor.png";
               // Commented-out line requires the frame to be resized/moved/etc.
               // before image is shown.  The lines following it show the image
               // immediately.
               //image = Toolkit.getDefaultToolkit().createImage(img);
               try {
                    image = ImageIO.read(new File(img));
               } catch (IOException ioe) {
                    ioe.printStackTrace();
                    image = null; // Create a default image to prevent NPE later
               setPreferredSize(new Dimension(400, 300));
          public void paintComponent(Graphics g) {
               g.drawImage(image, 0,0, null);//getX(), getY(), null);
}

Similar Messages

  • Alert message is needed at the time of creation ,if it reaches ,the maximu

    DEAR SA EXPERTS,
    Can you please me that alert message is needed at the time of creation ,if it reaches ,the maximum stock level (Stock+level)
    Thanks
    Mohit

    Hi,
    Please refer the below links.
    Alert Message
    Re: Alert Message
    Hope it helps you.
    Thanks.

  • Help needed in optimizing painting logic

    Hi,
    I am working on a Applet where i have to do a lot of painting, the applet is kind of microsoft project, where u can define a activity as a rectangle and then u can select the rectangle and drag it to some other date,
    i am posting a code below, which i am using to draw all the rectangles,
    but some times when there is a lot of data scrolling is really very slow
    Can any one look at the code, and let help me optimize it,
    U can copy the code, compile and run it to see what i mean by slow,
    just in class data , change the value 600 to some thing less like 50 and it works very fast
    //start code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    public class TestDisplaySize extends JFrame
         private     JScrollPane scrollPane ;
         private MyPanel panel ;
         public TestDisplaySize()
              super("layered pane");
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              panel = new MyPanel();
              scrollPane = new JScrollPane(panel);
              Container contentPane = this.getContentPane();
              contentPane.add(scrollPane, BorderLayout.CENTER);
              setSize(new Dimension(800,600));
              this.setVisible(true);
              JViewport viewPort = scrollPane.getViewport();
         class MyPanel extends JPanel
              private int height;
              private int last;
              private Data data;
              public MyPanel()
         this.setBackground(Color.white);
         this.setOpaque(true);
         data = new Data();
         int size = data.getSize();
         height = size * 50;     
         last = data.getDataSize(0);
         int last1 = last -1;
         int length = data.getX(0, last1) + 100;
         System.out.println ("Lenght " + length + " height " + height);
         setPreferredSize(new Dimension(length, height) );     
         public void paintComponent(Graphics g)
    super.paintComponent(g);
    setBackground(Color.white);
    Rectangle r = scrollPane.getViewport().getViewRect();
    g.setClip((Shape)r);
    g.setColor(Color.blue);
    int x = 0;
    for(int i = 0; i < last ; i++)
         x +=60;
         g.drawLine(x, 0, x, height);
         g.drawString(String.valueOf(i), x, 10);
    int size = data.getSize();
    int width = 30;
    int height = 20;
    int yAxis = 20;
    g.setColor(Color.cyan);
    for(int i = 0; i < size; i++)
         int dataSize = data.getDataSize(i);
         for(int k = 0; k < dataSize; k++)
              int xAxis = data.getX(i, k);
              g.fill3DRect(xAxis, yAxis, width, height, true);
         yAxis = yAxis + 50;
    private class Data
              private ArrayList totalData = new ArrayList();
              public Data()
                        for(int i = 0; i < 600; i++)
                        ArrayList data = new ArrayList();
                        int l = 50;
                        for(int k = 0; k < 600; k++)
                             data.add(new Integer(l));
                             l = l + 50;
                        totalData.add(data);
              public int getSize()
                   return totalData.size();     
              public int getDataSize(int i)
                   return ((ArrayList)totalData.get(i)).size();     
              public int getX(int x, int y)
                   ArrayList data = (ArrayList)totalData.get(x);
                   Integer i = (Integer)data.get(y);
                   return i.intValue();
         public static void main(String args[])
         new TestDisplaySize();

    You should only paint what is visible. For example if you are presenting a grid of 100 x 100 boxes. And each box is 20 pixels wide and 20 pixels high, then that would create an <image> the size of 2000 x 2000. That is big ;-)
    What you want to do, is calculate what portion of the <image> that is viewable in your scrollpane and then only perform the paint operations on those boxes. For example, if the viewports width is 200 and its hieght is 80, then you should only paint 10 x 4 boxes (40 boxes total, each 20x20 pixels in size) -- The trick is figuring out what boxes need to be painted.!! I'll leave that up to you, but should be able to find code examples on the net doing something of this sort.
    Hope this helps, and makes sense.
    Cory

  • Need code for Sales order creation in oops using xi as integration server

    Need code for Sales order creation in oops using xi as integration server.

    hi rocky,
              could you pls give a bit explanation on what you are expecting.
    regards,
    Pavan

  • In CS5: what kind of graphic board i need, If I paint it stutter!

    In CS5: what kind of graphic board i need, If I paint it stutter!

    Without any system information nobody can advise. What operating system? What system specs? What graphics hardware do you use currently? What input device? What settings in Photoshop? We could tell you to buy the latest and greatest card out there, but that might not at all resolve your issue because it#s caused by something else....
    Mylenium

  • Need of buffering in table creation.

    what is need of buffering in table creation and data class and delivey class

    Definition
    The name table (nametab) contains the table and field definitions that are activated in the SAP System. An entry is made in the Repository buffer when a mass activator or a user (using the ABAP Dictionary, Transaction SE11) requests to activate a table. The corresponding name table is then generated from the information that is managed in the Repository.
    The Repository buffer is mainly known as the nametab buffer (NTAB), but it is also known as the ABAP Dictionary buffer
    The description of a table in the Repository is distributed among several tables (for field definition, data element definition and domain definition). This information is summarized in the name table. The name table is saved in the following database tables:
    • DDNTT (table definitions)
    • DDNTF (field descriptions)
    The Repository buffer consists of four buffers in shared memory, one for each of the following:
    Table definitions TTAB buffer Table DDNTT
    Field descriptions FTAB buffer Table DDNTF
    Initial record layouts IREC buffer Contains the record layout initialized depending on the field type
    There are two kinds of table buffers:
    • Partial table buffers
    • Generic table buffers
    Check this link for more details.
    http://www.abapprogramming.blogspot.com/2007/11/buffering-in-sap-abap.html
    Regards,

  • Need help with paint (here my code)

    hi, i have problem with my paint method, if i put super.paint(g); all work perfectly but when you draw the program refresh all time, and does like flash effect taht i dotn want (test the code you'll see what im talking about) , and if i dont put super.paint(g) my component didnt paint... please help me, i know taht is a little bug, but i didnt have any kind of problem with swing before..
    thx
    //Debut imports
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    //Fin imports
    //  Class: soudure
    public class soudure extends JApplet implements MouseListener, MouseMotionListener, ChangeListener
        //Debut Declarations
        boolean dessinConfig = false; //Savoir quand on utilise paint pour config
        Image img; //Image a dessiner
        int x = -1; //Sert pour savoir le point x de la souris
        int y = -1; //Sert pour savoir le point y de la souris
        int ovalHeight = 10; //Set la hauteur de l'oval
        int ovalWidth = 10; //Set la largeur de l'oval
        JLabel xCoord, //Coordonner de la souris X
               yCoord, //Coordonner de la souris Y
               lVoltage, //Identifie le voltage
               lAmperage; //Indeitifie l'amperage
        JPanel config, //Panel de configuration
               dessin, //Panel de dessin
               info; //Panel d'info
        JSlider voltage, //Set le voltage
                amperage; //Set l'amperage
        Vector sauvOvalXY; //Sauvegarde les points x et y des ovals
        Vector sauvOvalWH;  //Sauvegarde les largeur et hauteur des ovals
        //Fin Declarations
        //  Fonction: init()
        public void init()
            //Debut Initialisations
            config = new JPanel();   
            dessin = new JPanel();
            info = new JPanel();
            xCoord = new JLabel("X Coord.: ");
            yCoord = new JLabel("Y Coord.: ");
            voltage = new JSlider(JSlider.VERTICAL, 15,30,15);
            lVoltage = new JLabel("Voltage  15 :");
            amperage = new JSlider(JSlider.VERTICAL, 100,400,100);
            lAmperage = new JLabel("Amperage  100 :");
    //      img = new Image();
          sauvOvalXY = new Vector();
          sauvOvalWH = new Vector();
            //Fin Initialisations
            //Debut set Background
            config.setBackground(Color.lightGray);       
            dessin.setBackground(Color.white);
            //Fin set Background
            //Debut set layout
            dessin.setLayout(null);
            //Fin Set Layout
            //Add les listener
            dessin.addMouseListener(this);
            dessin.addMouseMotionListener(this);
            voltage.addChangeListener(this);
            amperage.addChangeListener(this);       
            //Fin Add listener
            //Divers settings
            dessin.setBorder(new MatteBorder(1,1,1,1,Color.black));
            config.setBorder(new MatteBorder(1,1,1,1,Color.black));
            info.setBorder(new MatteBorder(1,1,1,1,Color.black));
            voltage.setSize(20,10);
            amperage.setSize(20,10);
            //Set Size
            getContentPane().setSize(500,500);
            config.setBounds(0,0,500,100);
            dessin.setBounds(0,100,500,300);
            info.setBounds(0,400,500,100);       
            //Fin set Size
            //Debut ajout Panel
            info.add(xCoord);
            info.add(yCoord);
            config.add(lVoltage);
            config.add(voltage);
            config.add(lAmperage);
            config.add(amperage);
            getContentPane().add(config,"North");
            getContentPane().add(dessin,"Center");
            getContentPane().add(info,"South");       
            //Fin ajout Panel       
        //Fin Fonction init()
        //  Fonction: mouseClicked(MouseEvent)
        public void mouseClicked(MouseEvent e)
        //Fin Fonction mouseClicked(MouseEvent)
        //  Fonction: mouseDragged(MouseEvent)
        public void mouseDragged(MouseEvent e)
            //Prend l'objet sur lequel l'event est fait
            Object obj = e.getSource();
            x = e.getX();
            y = e.getY();
            //JPanel Dessin
            if(obj == dessin)
                repaint();
                positionSouris(e);
            //Fin JPanel dessin
        //Fin Fonction mouseDragged(MouseEvent)
        //  Fonction: mouseEntered(MouseEvent)
        public void mouseEntered(MouseEvent e)
            //positionSouris(e);
        //Fin Fonction mouseEntered(MouseEvent)
        //  Fonction: mouseExited(MouseEvent)
        public void mouseExited(MouseEvent e)
            //Met les coords de la souris a 0
            xCoord.setText("X Coord.: 0");
            yCoord.setText("Y Coord.: 0");
        //Fin Fonction mouseExited(MouseEvent)
        //  Fonction: mouseMoved(MouseEvent)
        public void mouseMoved(MouseEvent e)
            positionSouris(e);
        //Fin Fonction mouseMoved(MouseEvent)
        //  Fonction: mousePressed(MouseEvent)
        public void mousePressed(MouseEvent e)
        //Fin Fonction mousePressed(MouseEvent)
        //  Fonction: mouseReleased(MouseEvent)
        public void mouseReleased(MouseEvent e)
        //Fin Fonction mouseReleased(MouseEvent)
        //  Fonction: paint(Graphics)
        public void paint(Graphics g)
            super.paint(g);
            g = dessin.getGraphics();
            //Verifie si rien n'a encore ete dragger
            if(x != -1)
                //Sauvegarde les infos
                sauvOvalXY.add(new Point(x,y));
                sauvOvalWH.add(new Point(ovalWidth,ovalHeight));
                //Dessine les sauvegarde
                int size = sauvOvalXY.size();
                for(int i=0;i<size;i++)
                    Point tmpXY = (Point)sauvOvalXY.get(i);
                    Point tmpWH = (Point)sauvOvalWH.get(i);
                    g.fillOval(tmpXY.x,tmpXY.y,tmpWH.x,tmpWH.y);
                g.fillOval(x,y,this.ovalWidth,this.ovalHeight);
    /*        //Si dessine pour panel config
            if(dessinConfig)
                g = config.getGraphics();
                g.drawImage(img,0,0,100,100,this);
               // dessinConfig = false;
        //Fin Fonction paint(Graphics)
        //  Fonction: positionSouris(MouseEvent)
        public void positionSouris(MouseEvent e)
            int tmpX = e.getX();
            int tmpY = e.getY();
            xCoord.setText("X Coord.: " + Integer.toString(tmpX));
            yCoord.setText("Y Coord.: " + Integer.toString(tmpY));
        //Fin Fonction positionSouris(MouseEvent)
        //  Fonction: stateChanged(ChangeEvent)
        public void stateChanged(ChangeEvent e)
            //Verifie lobject actuel
            Object obj = e.getSource();
            //Voltage
            if(obj == voltage)
                int tmpVoltage = voltage.getValue();
                lVoltage.setText("Voltage  " + Integer.toString(tmpVoltage) + " :");
            //Fin voltage
            else
                //Voltage
                if(obj == amperage)
                    int tmpAmperage = amperage.getValue();
                    lAmperage.setText("Amperage  " + Integer.toString(tmpAmperage) + " :");
                //Fin voltage       
        //Fin Fonction stateChanged(ChangeEvent)
    }

    Hi,
    For Swing components you need to override the paintComponent method instead of paint. In your case you can't do that with the approach you have taken. Here is how you can do it:
    1. Remove your paint method
    2. Change your creation of the dessin JPanel and override its' paintComponent method using an anonymous class.
        dessin = new JPanel()
                    public void paintComponent( Graphics g )   
                      super.paintComponent(g);      
                      //Verifie si rien n'a encore ete dragger 
                      if(x != -1)       
                        //Sauvegarde les infos
                        sauvOvalXY.add(new Point(x,y));
                        sauvOvalWH.add(new Point(ovalWidth,ovalHeight));
                        //Dessine les sauvegarde          
                        int size = sauvOvalXY.size(); 
                        for(int i=0;i<size;i++)         
                          Point tmpXY = (Point)sauvOvalXY.get(i);
                          Point tmpWH = (Point)sauvOvalWH.get(i);
                          g.fillOval(tmpXY.x,tmpXY.y,tmpWH.x,tmpWH.y);
                        g.fillOval(x,y,ovalWidth,ovalHeight);
                 };This will allow you to override the correct method and still use all of your applet class variables. Notice that I have removed the line getting the graphics of dessin because it is now being passed into the paintComponent method.
    The two steps above should remove any flashing that you may have had.
    Regards,
    Manfred.

  • Help needs on Report Painter

    Hi friends,
    I needs some information on Report Painter.
    I already searched in help.sap.com.
    but i cannot get these below information.
    Please help me out. it is very urgent for me.
    1.what are the general Tcodes used in this ?
    2.when and where should  we use report painter concept over standard reporting ?
    3. Is report painter exclusively used for any specific module like Project systems, FI/CO. or it can be used across all the SAP Functional Modules?
    4. I tried to create Report using Report painter Tcode CJE4
    then i got some basic doubts as below?
    a) what is difference between Project report and Summarization reports for project in report painter?
    b)Is it mandatory to create Form then attaching this Form to Report?
    c)what is difference in Two Axes, One axis with key figure,
    One axis without key figure structure ?
    d) what is meant by Key figure and Characteristics in this ?
    Thanks in advance.
    Regards,
    Sateesh

    Report painter
    the below Pdf should help you
    http://www.virtuosollc.com/PDF/Get_Reporter.pdf
    Reward points..

  • Need Sample Code for Vendor creation using JAVA API

    Hi,
    I have a scenario like Vendor creation using <b>Java API</b>.
    1.I have Vendors (Main) Table.
    2.I have <b>look up</b> tables like Account Group.
    3.Also <b>Qualifier table</b>(Phone numbers) too.
    Could you please give me the sample code which helps me to create Vendor records using Java API?
    <b>I need Code samples which should cover all of the above scenario.</b>
    <b>Marks will be given for the relevent answers.</b>
    Best Regards
    PK Devaraj

    Hi Devraj,
    I hope the below code might solve all your problem:-
    //Adding Qualified field
    //Creating empty record in Qualifed table 
    //Adding No Qualifiers
    Record qualified_record = RecordFactory.createEmptyRecord(new TableId(<TableId>));
    try {
    qualified_record.setFieldValue(new FieldId(<fieldId of NoQualifier), new StringValue(<StringValue>));//Adding No Qualifier
    catch (IllegalArgumentException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    catch (MdmValueTypeException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    //Creating Record in Qualified table
    CreateRecordCommand create_command = new CreateRecordCommand(connections);
    create_command.setSession(sessionId);
    create_command.setRecord(qualified_record);
    try
    create_command.execute();
    catch(Exception e)
    System.out.println(e.toString());
    RecordId record_id = create_command.getRecord().getId();
    //Adding the new record to Qualifed Lookup value and setting the Yes Qualifiers
    QualifiedLookupValue lookup_value = new QualifiedLookupValue();
    int link = lookup_value.createQualifiedLink(new QualifiedLinkValue(record_id));
    //Adding Yes Qualifiers
    lookup_value.setQualifierFieldValue(0 , new FieldId(<FieldID of Yes Qualifier>) , new StringValue(<StringValue>));
    //Now adding LookUP values
    //Fetch the RecordID of the value selected by user using the following function
    public RecordId getRecordID(ConnectionPool connections , String sessionID , String value , String Fieldid , String tableid)
    ResultDefinition rsd = new ResultDefinition(new TableId(tableid));
    rsd.addSelectField(new FieldId(Fieldid));
    StringValue [] val = new StringValue[1];
    val[0] = new StringValue(value);
    RetrieveRecordsByValueCommand val_command = new RetrieveRecordsByValueCommand(connections);
    val_command.setSession(sessionID);
    val_command.setResultDefinition(rsd);
    val_command.setFieldId(new FieldId(Fieldid));
    val_command.setFieldValues(val);
    try
         val_command.execute();
    catch(Exception e)
    RecordResultSet result_set = val_command.getRecords();
    RecordId id = null;
    if(result_set.getCount()>0)
         for(int i = 0 ; i < result_set.getCount() ; i++)
         id = result_set.getRecord(i).getId();     
    return id;
    //Finally creating the record in Main table
    com.sap.mdm.data.Record empty_record = RecordFactory.createEmptyRecord(new TableId("T1"));
    try {
         empty_record.setFieldValue(new FieldId(<FieldId of text field in Main table>),new StringValue(<StringValue>));
         empty_record.setFieldValue(new FieldId(<FieldId of lookup field in Main table>), new LookupValue(<RecordID of the value retrieved using the above getRecordID function>));
    empty_record.setFieldValue(new FieldId(<FieldId of Qualified field in Main table>), new QualifiedLookupValue(<lookup_value>));//QualifiedLookUp  value Retrieved above
    } catch (IllegalArgumentException e1) {
    // TODO Auto-generated catch block
         e1.printStackTrace();
    } catch (MdmValueTypeException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
    //Actually creating the record in Main table
    CreateRecordCommand create_main_command = new CreateRecordCommand(connections);
    create_main_command.setSession(sessionId);
    create_main_command.setRecord(empty_record);
    try
         create_main_command.execute();
    catch(Exception e)
         System.out.println(e.toString());
    Thanks
    Namrata

  • Need help with paint() within applet

    Hi,
    I am having some problems in using the paint() method within an applet.
    I need to use drawString() in the paint() method.
    However, I discovered that when i used drawString() in paint() method.
    It clears the background which has other GUI components wipe out.
    Pls help, thanx
    Sample code:
    public class watever extends javax.swing.JApplet {
    //initialize some components and variables
    public void init() {
    //adding of components to contentPane
    public void paint(Graphics g) {
    g.drawString("The variable is " + sum, 80, 80);
    }

    super.paint(g) the paint method draws the components to, so if you override it and then never tell it to draw the components they don't get drawn.

  • Help needed on Report painter

    Hi All,
    I have a requirement where i have to copy standard cost center report S_ALR_87013611 and change the G/L account to Alternative account and text.
    how do i copy this report painter report and modify the G/L account as required.
    i haven't worked on report painter .
    Points guaranteed !!!!
    Thanks & Regards,
    Raghavendra

    Hi,
    The Transaction code to create creating report writer it is GR31 and report painter is GRR1 and for .
    Reaport Painter allows you to create reports using data from SAP application components, which you can adapt to meet your individual requirements.
    Many of your reporting requirements can already be met by using the standard reports provided by various SAP application components. If these SAP standard reports do not meet your reporting needs, Report Painter enables you to define your specific reports quickly and easily.
    Report Painter fulfills a function similar to Report Writer, but is easier to use. Most of the functions found in Report Writer have been built into Report Painter; however, you do not need to be familiar with all Report Writer concepts (such as Sets) in order to use Report Painter.
    When executing a Report Painter report, it is displayed by the system in Report Writer format. You thus have access to the same functions as for Report Writer reports defined in the same way, and can combine Report Painter and Report Writer reports together in a report group.
    Report Painter uses a graphical report structure, which forms the basis for your report definition and displays the rows and columns as they appear in the final report output.
    To facilitate report definition, you can use many of the standard reporting objects provided by SAP (such as libraries, row/column models, and standard layouts) in your own specific reports. When you define a Report Painter report you can use groups (sets). You can also enter characteristic values directly.
    Advantages of Report Painter include:
    Flexible and simple report definition
    Report definition without using sets
    Direct layout control: The rows and columns are displayed in the report definition as they appear in the final report output, making test runs unnecessary.
    Hope this helps u.
    Regards,
    Seema.

  • Need Documents on New Role Creation in SAP

    Hi All,
    i am new to SAP Security and i would like to grow in this field,
    Can any one send me the links for the documents on creation of new roles, objects, Authorizations, transactions etc.
    Thanking you in Advance,
    Savitha.

    Hi,
    I guess you should look on Google for ADM940 and ADM950,
    Its a very detailed book for what ou want.
    Indeed to help you out, Its a very very simple task. But when you read this book keep in mind that there are 3 kinds of roles, Single roles, Derived roles and composite roles.
    Just to give you a heads up :
    Single role :  Role which has Authorization and data is restricted via company code and filed level values
    Derived role : these are derived from Single roles or you can say master role. Difference between single role and derived role is that you can derive say 10 roles from single role however company code can be manage in derived roles.
    So generally how it works is one create a master role which has all the required authorization. Now you don't want people in australia sould approve orders for Texas, US.
    Now there are hundred of companies department accross the glob. you don't want to end up creating hundreds of roles. so you create one master role and then you create derive role from that master role which is most of the time master role replica (keep in mind most of the time but not always so you have to be very carefull) now in derived role all you have to maintain is company codes.
    all the authorizations for all the objects and fields come from master role.
    I hope i am making sense.
    Composite role : its a collection of single and derived roles. Keep in mind you can not put composite role into composite role.
    That was just a heads up you need to read ADM940 and ADM950.

  • Need to read/paint large images fast. Help!

    Hello Java community,
    I am having trouble writing a program which can read large image files from disk (~ 1-2 MB) and paint them to the screen while maintaining a frame rate of 15 or 20 fps. Right now I am doing this through a Producer/Consumer scheme. I have one thread which constantly creates ImageIcons (using the constructor which accepts a String file path), and places them on a blocking queue (production) with a maximum capacity of 5 or 10. I have a second thread which removes an image from the queue (consumption) and paints it to the JFrame every so many milliseconds to honor the frame rate.
    My problem is that this approach is not fast enough or smooth enough. With smaller images it works fine, but with larger images it cannot maintain a high frame rate. It also seems to consume more memory than it should. I am assuming that once I paint a new ImageIcon, the old one goes out of scope and is freed from memory by the Garbage Collector. However, even with a queue capacity of 5 or 10, I am getting out-of-memory exceptions. I plan on trying the flush() method of the Image class to see if that helps to recover resources. After searching around a bit, I see that there are many different ways to read/load an image, but giving a local path to an ImageIcon and letting it load the image seems to be a safe way to go, especially because in the documentation for ImageIcon, it says that it pre-loads the image using Media Tracker.
    Any help, ideas, or links would be appreciated!
    Thanks,
    Elliot

    Thanks for another insightful response.
    I've played a bit more, so let me update you. I am preloading images, the blocking queue (FIFO) is full when the animation begins. Right now, the queue capacity is 10, but for smaller images it can be closer to 40 or 50. The image reader queue reads images and places them in this queue. Oddly, the problem does not seem to be that the reader thread can't keep up. I added a print statement which displays the size of the queue before each removal and it remains very close to the capacity, at least for the my test images which are only 400 x 400, approximately 100 KB each.
    I've tried animating the images in two distinct ways. My first approach, as I mentioned in the original question, was to animate the images using purely swing components and no manual painting of any kind. This is always nice because it frames the image perfectly and the code is minimal. To accomplish this I simply had the image reader thread pass in the image path to the constructor of ImageIcon and put the resulting ImageIcon in the queue. The animator thread had a simple swing timer which fired an ActionEvent every so-many milliseconds (in the event dispatch thread). In the actionPerformed method I simply wrote a few lines to remove the head of the queue and I used the JLabel setIcon(ImageIcon) to update the display. The code for this was very nice, however the animation was choppy (not flickering).
    In my second approach, which was a bit longer, I created a class called AnimationPanel which extended JPanel and implemented Runnable. I simply overrode paintComponent and inside I painted a member Image which was set in the thread loop. Rather than storing ImageIcons, the queue stored Images. The reader thread used ImageIO.read(...) to generate an Image. I used simple logic in the thread loop to monitor the fps and to fire repaints. This approach suffered from the same problem as the one above. The animation was choppy.
    I found the following things to be true:
    - the reader can keep up with the animator
    - if I run the image reader and perform a basic polygon animation, both of my approaches animate smoothly at high frame rates. In other words, it's not the work (disk reads) being done by the reader that is causing the lag
    - I believe the slowness can be attributed to the following calls: label.setIcon(imageIcon) or g.drawImage(image, 0, 0, this). This leads me to believe that the images are not fully processed as they are being placed on the queue. Perhaps Java is waiting until they are being used to fully read/process the images.
    - I need to find a way to process the images fully before trying to paint them, but the I felt that my approaches above were doing that. I considered have the reader frame actually generate a JLabel or some object that can be displayed without additional processing.
    - your idea about AWT components is a good one and I plan on trying that.
    Elliot

  • Help needed with a paint program

    Hi, I am writing a program to work as a paint application. I have all the necessary buttons. One of my buttons needs to be able to add a small image to the painting frame by clicking the mouse onto the screen...for example, to display a picture of a house, I click the house button which then puts my house picture onto the scribble panel wherever I click the mouse. My problem is that I am new to java and I am stuck on how I can do this. I have put all the code on here which I have. If any one knows the code which I can add to make this work I would very much appreciate it as it is driving me insane!
    Many thanks....
    CODE "DrawingTools.java".............................
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class DrawingTools {
    public static void main (String [] args) {
         Toolkit tk = Toolkit.getDefaultToolkit(); // get system dependent information
    Dimension dim = tk.getScreenSize(); // encapsulate width and height of system
    JFrame f = new DrawingToolFrame();
    f.setSize(800, 550);
    f.setTitle("Drawing Tool v1.10");
    f.setIconImage(tk.getImage("Paint.gif"));
    f.setVisible(true);
    f.setResizable(false);
    class DrawingToolFrame extends JFrame implements ActionListener {
    private JCheckBox checkNormal, checkBold, checkDotted, checkSpray;
    // private JRadioButton orBlack, orBlue, orRed, orYellow, orNormal, orBold, orDotted, orSpray;
    private JButton boldButton, dottedButton, sprayButton;
    private JButton blackButton, blueButton, yellowButton, redButton, greenButton, houseButton, tvButton, starButton;
    private ScribblePanel scribblePanel;
    private JButton scribbleButton, undoButton, newButton, quitButton;
    private JMenuItem newItem, quitItem, undoItem, houseItem, tvItem, starItem,/* normalItem,*/ boldItem, dottedItem, sprayItem, blackItem, blueItem, redItem, yellowItem, greenItem;
    public DrawingToolFrame() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
    Container contentPane = getContentPane();
    JMenuBar menuBar = new JMenuBar();
         setJMenuBar(menuBar);
         JMenu fileMenu = new JMenu("File");
         newItem = new JMenuItem("New");
         newItem.setMnemonic(KeyEvent.VK_N); //add Alt-N to New short-cut
         newItem.addActionListener(this);
         fileMenu.add(newItem);
         quitItem = new JMenuItem("Quit");
         quitItem.setMnemonic(KeyEvent.VK_Q); //add Alt-Q to Quit short-cut
         quitItem.addActionListener(this);
         fileMenu.add(quitItem);
         menuBar.add(fileMenu);
         JMenu editMenu = new JMenu("Edit");
         undoItem = new JMenuItem("Undo");
         undoItem.addActionListener(this);
         editMenu.add(undoItem);
         menuBar.add(editMenu);
         JMenu shapeMenu = new JMenu("Shape");
         houseItem = new JMenuItem("House");
         houseItem.addActionListener(this);
         shapeMenu.add(houseItem);
         tvItem = new JMenuItem("Television");
         tvItem.addActionListener(this);
         shapeMenu.add(tvItem);
         starItem = new JMenuItem("Star");
         starItem.addActionListener(this);
         shapeMenu.add(starItem);
         menuBar.add(shapeMenu);
    JMenu optionMenu = new JMenu("Option");
    JMenu lineMenu = new JMenu("Line");
         optionMenu.add(lineMenu);
              //normalItem = new JMenuItem("Normal");
              //normalItem.addActionListener(this);
              //lineMenu.add(normalItem);
              boldItem = new JMenuItem("Bold");
              boldItem.addActionListener(this);
              lineMenu.add(boldItem);
              dottedItem = new JMenuItem("Dotted");
              dottedItem.addActionListener(this);
         lineMenu.add(dottedItem);
         sprayItem = new JMenuItem("Spray");
         sprayItem.addActionListener(this);
         lineMenu.add(sprayItem);
         JMenu colourMenu = new JMenu("Colour");
         optionMenu.add(colourMenu);
              blackItem = new JMenuItem("Black");
              blackItem.addActionListener(this);
              colourMenu.add(blackItem);
              blueItem = new JMenuItem("Blue");
              blueItem.addActionListener(this);
              colourMenu.add(blueItem);
              redItem = new JMenuItem("Red");
              redItem.addActionListener(this);
         colourMenu.add(redItem);
         yellowItem = new JMenuItem("Yellow");
         yellowItem.addActionListener(this);
         colourMenu.add(yellowItem);
         greenItem = new JMenuItem("Green");
                   greenItem.addActionListener(this);
         colourMenu.add(greenItem);
         menuBar.add(optionMenu);
    JPanel p = new JPanel();
    ImageIcon scribbleIcon = new ImageIcon("Scribble.gif");
    scribbleButton = new JButton("Scribble", scribbleIcon);
    scribbleButton.setMnemonic(KeyEvent.VK_S); //add Alt-S to Undo short-cut
    scribbleButton.setToolTipText("Click this button and you can draw free hand lines.");
    p.add(scribbleButton);
    //scribbleButton = addJButton("Scribble", p);
    p.add(Box.createHorizontalStrut(20));
    ImageIcon undoIcon = new ImageIcon("Undo.gif");
    undoButton = new JButton("Undo", undoIcon);
    undoButton.setMnemonic(KeyEvent.VK_U); //add Alt-U to Undo short-cut
    undoButton.setToolTipText("Undo the last step");
    p.add(undoButton);
    //undoButton.addActionListener(this);
    p.add(Box.createHorizontalStrut(20));
    ImageIcon newIcon = new ImageIcon("New.gif");
    newButton = new JButton("New", newIcon);
    newButton.setMnemonic(KeyEvent.VK_N); //add Alt-N to New short-cut
    newButton.setToolTipText("Make a new Drawing");
    p.add(newButton);
    p.add(Box.createHorizontalStrut(20));
    ImageIcon quitIcon = new ImageIcon("Door.gif"); //add icon to button
    quitButton = new JButton("Quit", quitIcon);
    quitButton.setMnemonic(KeyEvent.VK_Q); //add Alt-Q to exit short-cut
    quitButton.setToolTipText("Click to Exit");
    p.add(quitButton);
    undoButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    scribblePanel.undo();}});
    scribbleButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    scribblePanel.repaint();}});
    newButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    scribblePanel.repaint();}});
    quitButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    System.exit(0);}});
    contentPane.add(p, "South");
    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(Box.createVerticalStrut(10));
    ImageIcon boldIcon = new ImageIcon("Bold.gif"); //add icon to button
    boldButton = new JButton("Bold", boldIcon);
    p.add(boldButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon dottedIcon = new ImageIcon("Dotted.gif"); //add icon to button
    dottedButton = new JButton("Dotted", dottedIcon);
    p.add(dottedButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon sprayIcon = new ImageIcon("Spray.gif"); //add icon to button
    sprayButton = new JButton("Spray", sprayIcon);
    p.add(sprayButton);
    /*     ButtonGroup groupA = new ButtonGroup();
         p.add(Box.createVerticalStrut(20));
         orNormal = addJRadioButton("Normal", true, groupA, p);
         p.add(Box.createVerticalStrut(20));
         orBold = addJRadioButton("Bold", false, groupA, p);
         p.add(Box.createVerticalStrut(20));
         orDotted = addJRadioButton("Dotted", false, groupA, p);
         p.add(Box.createVerticalStrut(20));
         orSpray = addJRadioButton("Spray", false, groupA, p);*/
    contentPane.add(p, "East");
    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(Box.createVerticalStrut(10));
    ImageIcon dIcon = new ImageIcon("Black.gif"); //add icon to button
    blackButton = new JButton("Black", dIcon);
    p.add(blackButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon eIcon = new ImageIcon("Blue.gif"); //add icon to button
    blueButton = new JButton("Blue", eIcon);
    p.add(blueButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon fIcon = new ImageIcon("Red.gif"); //add icon to button
    redButton = new JButton("Red", fIcon);
    p.add(redButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon gIcon = new ImageIcon("Yellow.gif"); //add icon to button
    yellowButton = new JButton("Yellow", gIcon);
    p.add(yellowButton);
    p.add(Box.createVerticalStrut(10));
    ImageIcon hIcon = new ImageIcon("Green.gif"); //add icon to button
    greenButton = new JButton("Green", hIcon);
    p.add(greenButton);
    p.add(Box.createVerticalStrut(30));
    ImageIcon houseIcon = new ImageIcon("house.gif");
    houseButton = new JButton("House", houseIcon);
    houseButton.setToolTipText("Click to add a house in the picture!");
    p.add(houseButton);
    //houseButton = addJButton("House", p);
    p.add(Box.createVerticalStrut(10));
    ImageIcon tvIcon = new ImageIcon("tv.gif");
    tvButton = new JButton("Television", tvIcon);
    tvButton.setToolTipText("Click to add a Television in the picture!");
    p.add(tvButton);
    //tvButton = addJButton("Television", p);
    p.add(Box.createVerticalStrut(10));
    ImageIcon starIcon = new ImageIcon("star.gif");
    starButton = new JButton("Star", starIcon);
    starButton.setToolTipText("Click to add stars in the picture!");
    p.add(starButton);
    //starButton = addJButton("Star", p);
    contentPane.add(p, "West");
    scribblePanel = new ScribblePanel();
    contentPane.add(scribblePanel, "Center");
    private JButton addJButton(String text, Container container) {
    JButton button = new JButton(text);
    container.add(button);
    return button;
    private JRadioButton addJRadioButton(String text, boolean on, ButtonGroup group, Container container) {
    JRadioButton button = new JRadioButton(text, on);
    group.add(button);
    container.add(button);
    return button;
    public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    if (source instanceof JMenuItem) {
    String arg = e.getActionCommand();
    if (arg.equals("Undo"))
    scribblePanel.undo();
    else if (arg.equals("New"))
    scribblePanel.repaint();
    else if (arg.equals("Quit"))
    System.exit(0);
    }

    The code posted just sends any data it receives back to the person who sent it. To get it to work there, you probably should flush after the println. I believe your mother taught you always to flush. It seems you have forgotten.

  • Needed urgent help for user creation in security manager in ODI 11g

    Hi Gurus,
    I have an urgent requirement in ODI security manager and i am completely helpless. We need specific steps for the user creation with sufficient priviledges. The detailed requirements are:
    1. There is a group of users under the framework team and these users should be able to edit the Knowledge modules only. All other objects (e.g. projects, interface, procedures or development related objects) should only be in read only mode for them.
    2. There is a group of users under the development team. The priviledges of these users should be mutually exclusive to that of the framework team users. i.e. the development team should be able to edit or delete all development related objects (e.g. projects, interface, proc etc.) but the knowledge modules should only be in read only mode for them.
    Now I will explain what i have tried out:
    I am working on ODI 11.1.1.5.
    I have created a user with NG DESIGNER and CONNECT profile. Dragged and dropped all the projects on the user and selected all methods in all repositories (check sign). However when i connect with that user i cannot open the KMs (as far as development team is concerned its fine) but i can also not open interfaces as well as procedures (which is not acceptable from development point of view).
    Also when i tried creating a user from the framework team point of view i could not see any option related to KMs (To give edit priviledge).
    Please help me out guys. I have also searched oracle documentation and believe me the security manager section is not very good. If you guys can help me out with specific steps it would be great (I have tried the hints given in oracle documentation and they dont work, the ODI security manager behaves strangely :-(
    Thanks in advance,
    SB

    Similar requirement here guys. Any pointers. I was able to achieve this by restricting development user from supervisor access. In that case the development user can not edit the interfaces. Any known defefct?

Maybe you are looking for