Draw image over Swing to mask.

I have a window and I've overridden it make it draw all of it's components and then draw images over them (on a back buffer and then flip so the swing shouldn't ever be seen).
It works perfectly and the swing components (JButtons and the like) catch the clicks when I click on the images masking them. The problem is when I click them for a very brief moment I see the Swing component come through. How is Swing doing this? Since I blt in a specific order and then flip. Somehow it is using the Graphics for the window directly - I overrode invalidate in a few ways but that just broke the components altogether.
Anyone masked Swing components with images using a BufferStrategy? I would love some advice.

AbstractButton (which JButton extends) calls JComponent.paintImmediately upon a click, so I don't think you can stop it without overriding AbstractButton and JButton (not recommended).
Either override the paint method for your components to look like your overlaid image or remove your Swing components and test the mouse click location in the MouseListener.
--Jon

Similar Messages

  • Draw image over jtable header

    hello, I am trying to draw an image (its a little image of a custom sort indicator) over the header of a jTable, but after extensive reading of the api docs about TableCellRenderer and DefaultTableCellRenderer I cannot come to a solution.
    What I want is something like this: let the renderer do the paint and after that I grab the graphics and draw the image over it...
    please let me know if I need to restate my problem

    I extended DefaultTableCellRenderer like you say in your article, but while doing so it lost the default Metal L&F. It become like an ordinary cell of the table. Below is the code:
    class DefaultTableHeaderCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column)
          super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
          //setIcon(getIcon(table, column));
          setBorder(UIManager.getBorder("TableHeader.cellBorder"));
          return this;
        protected Icon getIcon(JTable table, int column) {
           ImageIcon icon = new ImageIcon("imagens/sortdown.png");
           return icon;
    }then in my class I call:
    this.getTableHeader().setDefaultRenderer(new DefaultTableHeaderCellRenderer());You can see I commented setIcon. It works, the icon is drawn, but this is not what I am after, I wanted to draw the icon over the Metal L&F. Also, is there a way to draw the icon at a specified position?
    thanks for the help

  • Draw line over Image??.. in Grid Format

    Hello frnds,
    what i want to do in my project is to draw image on JPanel with grid lines.. ??
    May be image in background and lines over image..
    I searched forum before but coulnt find appropriate thread.. please help me out??
    gervini

    from within the JPanel's paint() method.In Swing components you should overide the paintComponent() method, not paint().

  • JMF - How to draw Circles over Video (JMF / Java2D / Swing)

    Hi there!
    I want to draw polygons over a playing video-panel, but they keep vanishing behind the video... Is there a way to bring them on top of the video canvas? The application which I'm going to develop should indicate ROIs on a playing video... This thread was inspiring, but didn't help at all...
    http://forum.java.sun.com/thread.jspa?forumID=28&threadID=612055

    Hi there!
    I want to draw polygons over a playing video-panel, but they keep vanishing behind the video... Is there a way to bring them on top of the video canvas? The application which I'm going to develop should indicate ROIs on a playing video... This thread was inspiring, but didn't help at all...
    http://forum.java.sun.com/thread.jspa?forumID=28&threadID=612055

  • Drawing pictures over others

    I'm trying to create a small applet. I'm getting an image from a intranet, it's a map of barcelona's street. User must be able to move a scroll bar, do zoom, print images, etc, but at the same time I need to paint over this image some other pictures, these images will get the same funcionality taht the first one, zoom, scroll, etc.
    I'm trying to use JAI, swing and awt objects but I don't get a result, I can do zoom or scroll to a planar image but I can't paint nothing over the image.
    I've been trying with ImageDisplay component but it can't show images gif, I need to read gif images, and the scroll is not working properly with that object.
    Do you have some suggestions?
    Can I do with bufferedImages?
    Thanks

    I'll send you the applet class:
    package net.visualapplet;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Font;
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Hashtable;
    import java.util.Properties;
    import java.util.Vector;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import javax.media.jai.RenderedOp;
    import javax.swing.ImageIcon;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JProgressBar;
    import java.awt.GridLayout;
    import net.visualapplet.listeners.GestionarEventsBoto;
    import net.visualapplet.listeners.GestionarEventsCampText;
    //Imprimir
    import net.visualapplet.print.Print;
    public class VisualApplet extends JApplet {
    protected String posX, posY;
    protected String resX, resY;
    protected String escala;
    protected ItinerariPanel panelImage;
    protected java.util.Vector vecSources;
    //Objecte Progress Bar amb texte
    public JProgressBar progressBar = new JProgressBar();
    public JLabel progressBarLabel = new JLabel("Cargando Imagen: ");
    protected final int MY_MINIMUM=0;
    protected final int MY_MAXIMUM=1000;
    protected int i=10;
         * Propietats que determinen els valors de la sessi� a passar al Servlet
         * Depenen del Servidor d'Aplicacions seran uns noms o altres
    private Properties sessionProperties;
         * Url de connexio al Servlet
         * Aquesta url vindra per parametre dins PARAM de Applet
    //private String urlConnexio;
    public String DNSServidor;
         * Tipus de Servidor al que ens connectem
    private String serverType;
         //Sets y Gets
         public void setPosX(String posX){
              this.posX = posX;
         public String getPosX(){
              return posX;
         //RESX
         public void setPosY(String posY){
              this.posY = posY;
         public String getPosY(){
              return posY;
         //RESX
         public void setResX(String resX){
              this.resX = resX;
         public String getResX (){
              return resX;
         //RESY
         public void setResY(String resY){
              this.resY = resY;
         public String getResY(){
              return resY;
         //ESCALA
         public void setEscala (String escala){
              this.escala = escala;
         public String getEscala (){
              return escala;
         //ImagePanel
         public void setPanelImage(ItinerariPanel panel){
              this.panelImage=panel;
         public ItinerariPanel getPanelImage(){
                   return panelImage;
         //Source
         public void setSources(java.util.Vector sources){
              this.vecSources = sources;          
         public java.util.Vector getSources(){
              return vecSources;          
    public void init() {
    Container objContainer = super.getContentPane();
    objContainer.setBackground( Color.white );
    Vector sources = new Vector();
    setSources(sources);
         //Inicializamos valores
         //posX="29820502";
         setPosX("29820502");
         //posY="84574955";
         setPosY("84574955");
         //resX="800";
         setResX("800");
         //resY="600";
         setResY("600");
         //escala="5000";          
         setEscala("5000");     
         //Progress Bar lo ponemos a invisible     
         progressBar.setMinimum(MY_MINIMUM);
         progressBar.setMaximum(MY_MAXIMUM);     
         progressBar.setVisible(false);
         progressBarLabel.setVisible(false);     
    protected String getImageUrl(String posX, String posY, String resX, String resY, String escala) throws Exception {
              Hashtable params = new Hashtable();
              //Convertimos valores a Double
              //Double DposX = new Double(posX);
              //Double DposY = new Double(posY);
              //java.lang.Double DresX = new Double(resX);
              //java.lang.Double DresY = new Double(resY);
              //java.lang.Double Descala = new Double(escala);
              params.put("");
              params.put("","");
              params.put("","");
              params.put("",posX);
              params.put("",posY);
              params.put("VN_ANTIALIASED","0");
              params.put("VN_BMPX",resX);
              params.put("VN_BMPY",resY);
              params.put("VN_ESCALA",escala);
              //posX="29820502";
              //posY="84574955";
              RequestManager manager = new RequestManager();
              return manager.getImageUrl("http://www.bcn.es/cgi-guia/bcnet",params);
    public void start() {
    try {
              JLayeredPane layers = getLayeredPane();
              JPanel cTop      = new JPanel();
              JPanel cBottom = new JPanel();
              JPanel cLeft     = new JPanel();
              JPanel cRightBoto = new JPanel();
              JPanel cCenter     = new JPanel();
              JPanel cRightText     = new JPanel();          
              JPanel cRightPanel     = new JPanel();
              JPanel cBottomBar     = new JPanel();
              JPanel cBottomPanel     = new JPanel();
              //Inicializamos valores
              //posX="29820502";
              //posY="84574955";
              //resX="800";
              //resY="600";
              //escala="5000";          
              //JPanel cComponents     = new JPanel();
              Container cComponents = getContentPane();
         String urlImage = getImageUrl(getPosX(),getPosY(),getResX(),getResY(),getEscala());
         //ImagePanel panel = new ImagePanel(urlImage);          
              RenderedOp rendered = JAI.create("url", new java.net.URL(urlImage));
              PlanarImage image = rendered.createInstance();
              java.util.Vector sources = getSources();
              //IMprimimos la imagen
              //Print imgPrintable = new Print();
              sources.addElement(image);
              //A�adimos la imagen que ira por encima
              sources.addElement(image2);
              setSources(sources);
         // A�adimos botones      
         ImageIcon leftButtonIcon = new ImageIcon("left.gif");
              ImageIcon rightButtonIcon = new ImageIcon("right.gif");
              ImageIcon upButtonIcon = new ImageIcon("up.gif");
              ImageIcon downButtonIcon = new ImageIcon("down.gif");
         JButton bLeft           = new JButton("Izq",leftButtonIcon);
              JButton bRight           = new JButton("Der",rightButtonIcon);
              JButton bUp               = new JButton("Arr",upButtonIcon);
              JButton bDown          = new JButton("Abj",downButtonIcon);
              JButton bBuscar          = new JButton("Buscar");
              JButton bImprimir      = new JButton("Imprimir");     
              Font font=new Font("SansSerif", Font.BOLD, 14);                    
              Color color = new Color(0,255,0);
              Graphics g = getGraphics();
              g.setColor(color);
              //A�adimos campos de texto y sus Etiquetas          
              JLabel labelPosX = new JLabel("Coordenada X");
              JLabel labelPosY = new JLabel("Coordenada Y");
              JLabel labelEscala = new JLabel("Escala");
              JLabel labelBlank = new JLabel(" ");
              labelPosX.setFont(font);          
              labelPosY.setFont(font);
              labelEscala.setFont(font);
              JTextField textPosX = new JTextField(10);                    
              JTextField textPosY = new JTextField(10);
              JTextField textEscala = new JTextField(10);
              //INicializamos con los valores de PosX y PosY
              textPosX.setText(getPosX());
              textPosY.setText(getPosY());
              textEscala.setText(getEscala());
              textPosX.setName("textPosX");
              textPosY.setName("textPosY");
              textEscala.setName("escala");
              textPosX.addActionListener(new GestionarEventsCampText(this));
              textPosY.addActionListener(new GestionarEventsCampText(this));
              textEscala.addActionListener(new GestionarEventsCampText(this));
              //ImageIcon imageIconCamion = new ImageIcon("up.gif");
              //JLabel imageLabel= new JLabel(imageIconCamion);
              //CanvasPanel miCanvas = new CanvasPanel();
         //JAIScalePanel panel = new JAIScalePanel(sources);
              ItinerariPanel panel = new ItinerariPanel(sources);                    
              setPanelImage(panel);
    //JTabbedPane tabbed = new JTabbedPane();          
              //A�adimos Escuchador de Eventos
              bLeft.addActionListener(new GestionarEventsBoto(this));
              bRight.addActionListener(new GestionarEventsBoto(this));
              bUp.addActionListener(new GestionarEventsBoto(this));
              bDown.addActionListener(new GestionarEventsBoto(this));
              bBuscar.addActionListener(new GestionarEventsBoto(this));
              bImprimir.addActionListener(new GestionarEventsBoto(this));
              // A�adimos elementos en su panel          
              cLeft.add(bLeft,BorderLayout.CENTER);
              cRightBoto.add(bRight,BorderLayout.CENTER);
              cTop.add(bUp,BorderLayout.CENTER);
              cBottom.add(bDown,BorderLayout.CENTER);               
              cBottomBar.add(progressBarLabel);     
              cBottomBar.add(progressBar);
              cCenter.add(panel,BorderLayout.CENTER);
    //          cCenter.add(miCanvas,BorderLayout.CENTER);
              //A�adimos Textfields y Labels al contenedor derecho          
              //Cambiamos su layout a tipo grid
              cRightText.setLayout(new GridLayout(13,1));     
              cRightText.add(labelPosX);
              cRightText.add(textPosX);
              cRightText.add(labelPosY);
              cRightText.add(textPosY);
              cRightText.add(labelEscala);
              cRightText.add(textEscala);     
              cRightText.add(labelBlank);
              cRightText.add(bBuscar);
              cRightText.add(bImprimir);
    //tabbed.addTab("General",panel);
    //Cremamos el container de 2 columans para meter
    //el contenedor con el boton derecha y los txtBox
              cRightPanel.setLayout(new GridLayout(1,2));
              cRightPanel.add(cRightBoto);
              cRightPanel.add(cRightText);
              //A�adimos 2 Paneles abajo
              cBottomPanel.setLayout(new GridLayout(2,1));
              cBottomPanel.add(cBottom);
              cBottomPanel.add(cBottomBar);
    //A�adimos componentes al contenedor principal
    cComponents.add(cLeft,BorderLayout.WEST);
              cComponents.add(cTop,BorderLayout.NORTH);
              cComponents.add(cRightPanel,BorderLayout.EAST);          
              cComponents.add(cBottomPanel,BorderLayout.SOUTH);
              cComponents.add(panel,BorderLayout.CENTER);               
              //tabbed.addTab("General",cComponents);               
              //getContentPane().add(tabbed);
              //getContentPane().add(cComponents);
              setSize(new Dimension(800,600));
    } catch (Exception exc) {
         System.err.println("Excepcion:" + exc.getMessage());
    public void paint(Graphics g) {
         //System.out.println();
    super.paint(g);
    public static void main( String args [] ) {
    JFrame app = new JFrame( "Swing JApplet (Application or Applet)" );
    app.setSize( 800, 600); //set Frame: width, height
    app.addWindowListener( //Register an anonymous class as a listener.
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    VisualApplet applet = new VisualApplet();
    applet.init(); applet.start();
    app.getContentPane().add( applet, BorderLayout.CENTER ); //add applet to center of frame.
    app.setVisible( true );
    } //main()
    //We have remove some confidential information that is not important, I'll sen you itinerariPanel, this class send a PlanarImage to JAIScalePanel in that place teh planarImage is put into scrollPanel and at the same time into jslider panel.
    We need to insert images over that image doesn't matter if we need to change from planarimage to bufferedimage.
    Itinerari Panel Class:
    package net.visualapplet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.image.BufferedImage;
    //Nuevos del dia 20 Mayo
    import javax.media.jai.PlanarImage;
    import java.awt.image.RenderedImage;
    import javax.media.jai.JAI;
    //Fin imports nuevos
    import javax.media.jai.RenderedImageAdapter;
    import net.visualapplet.gui.JAIScalePanPanel;
    * @author Xavier Escudero
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class ItinerariPanel extends JAIScalePanPanel {
         private java.util.Vector sourceImages;
         public ItinerariPanel(java.util.Vector sourceImages) {
              super(sourceImages);
              this.sourceImages = sourceImages;
         /* (non-Javadoc)
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              RenderedImageAdapter ria = new RenderedImageAdapter(getSource(0));
              BufferedImage bi = ria.getAsBufferedImage();
              Graphics2D g2 = bi.createGraphics();          
              // Asumimos que "x, y, diam" son variables de instancia
              Ellipse2D circulo =
                   new Ellipse2D.Double(10,10,100,100);          
              g2.draw(circulo);
              PlanarImage imatge = (PlanarImage)sourceImages.elementAt(1);
              RenderedImageAdapter ria2 = new RenderedImageAdapter(imatge);
              BufferedImage bi2 = ria.getAsBufferedImage();
              //System.out.println("Imagen buffered "+bi2);
              //RenderedImage imr2 = JAI.create("file",imatge);          
              //g2.drawImage(bi2,20,20,this);
              //g.drawImage(bi2,0,0,this);                    
    I know that may be these code is quite confuse. I'm sorry, we need to read a picture and get the chance to put some images over the firs one, do scroll, zoom, tootips, etc.

  • How can I draw image in a vbean?

    How can I draw image in a vbean?
    this is my code :
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         boolean ImageLoaded = false;
         public void paint(Graphics g) {
              if (ImageLoaded) {
                   System.out.println("yes~~~");
                   g.drawImage(img, 0, 0, null);
              } else
                   System.out.println("no~~~");
         public boolean imageUpdate(Image img, int infoflags, int x, int y, int w,
                   int h) {
              if (infoflags == ALLBITS) {
                   System.out.println("yes");
                   ImageLoaded = true;
                   repaint();
                   return false;
              } else
                   return true;
         public void init(IHandler arg0) {
              super.init(arg0);
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   Image offScreenImage = createImage(size().width, size().height);
                   Graphics offScreenGC = offScreenImage.getGraphics();
                   System.out.println(offScreenGC.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    but when I run it in forms
    when it run Graphics offScreenGC = offScreenImage.getGraphics();
    It throw a exception:
    java.lang.NullPointerException     at com.avicit.aepcs.calendar.PrintEmailLogo.init(PrintEmailLogo.java:72)     at oracle.forms.handler.UICommon.instantiate(Unknown Source)     at oracle.forms.handler.UICommon.onCreate(Unknown Source)     at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)     at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)     at oracle.forms.engine.Runform.processMessage(Unknown Source)     at oracle.forms.engine.Runform.processSet(Unknown Source)     at oracle.forms.engine.Runform.onMessageReal(Unknown Source)     at oracle.forms.engine.Runform.onMessage(Unknown Source)     at oracle.forms.engine.Runform.processEventEnd(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)     at java.awt.Component.dispatchEventImpl(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.EventQueue.dispatchEvent(Unknown Source)     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)     at java.awt.EventDispatchThread.run(Unknown Source)
    I change it to:
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JFrame;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         public void paint(Graphics g) {
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   g.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void init(IHandler arg0) {
              super.init(arg0);
    But it display nothing.
    It isn't paint continuous.
    what's wrong in my vbean?
    please help me.

    The following code works fine for me:
    package oracle.forms.fd;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.CustomEvent;
    import oracle.forms.ui.VBean;
    public class test extends VBean {
      private URL url;
      private URL m_codeBase; 
      private Image img;
    public void paint(Graphics g) {
      // draw the image
      g.drawImage(img, 0, 0, this);
    public void init(IHandler arg0) {
       super.init(arg0);
       // load image file
       img = loadImage("file:///c:/coyote.jpg");   
    public test()
        super();
       *  Load an image from JAR file, Client machine or Internet URL  *
      private Image loadImage(String imageName)
        URL imageURL = null;
        boolean loadSuccess = false;
        Image img = null ;
        //JAR
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          try
            img = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            return img ;
          catch (Exception ilex)
            System.out.println("Error loading image from JAR: " + ilex.toString());
        else
          System.out.println("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          System.out.println("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else if(imageName.toLowerCase().startsWith("file:"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
              System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          System.out.println("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
                    System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          System.out.println("Error image " + imageName + " could not be located");
        return img ;
    }Francois

  • Question about setting the background from an image over the internet.

    Hello ,
    If I want the background of my panel to be set from an image over the internet directly do I just add that URL right away like this :
    protected final static String imagePath = "http://www.engr.wisc.edu/2010/background.jpg";
       icon = new ImageIcon(AuthScreen.imagePath);
            JPanel panel = new JPanel(){
                protected void paintComponent(Graphics g)
              Dimension d = getSize();
              g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
              super.paintComponent(g);
              };instead of this :
    protected final static String imagePath = "d:\\javaapps\\bg.jpg";cuz I did that but it isnt working .
    Thanks.

    I don't see how, try it out:
    import java.awt.*;
    import java.awt.image.*;
    import java.net.URL;
    import javax.swing.*;
    import javax.imageio.*;
    public class ForumJunk{
      ForumJunk(){
        JFrame f = new JFrame("Forum Junk");
        JPanel p = new MyJPanel();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.pack();
        f.setVisible(true);
      public static void main(String[] args) {
        new ForumJunk();
      class MyJPanel extends JPanel{
        BufferedImage bi = null;
        MyJPanel(){
          try{
            bi = ImageIO.read(new URL("http://www.kodiakfishingbc.com/Editor/assets/chris03resize.jpg"));
            this.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
          }catch(java.io.IOException e){
            System.out.println(e.toString());
        public void paintComponent(Graphics g){
    //      super.paintComponent(g);
          ((Graphics2D)g).setBackground(Color.green);
          g.clearRect(0, 0, bi.getWidth(), bi.getHeight());
          g.drawImage(bi,0, 0, this);
          super.paintComponent(g);
    }

  • And again - how do I superimpose an image over a moving image?

    So I am beginning to work this all out...
    I have cropped an image using motion which is looking great, except that the image (which is someone's head) is square because I used 'crop' in motion, any ideas how to make the edges curved?
    The next step is working out how to keep the superimposed image over the head of the person in the video if they move? ie so it tracks the original image in movement?
    Thank you all for your help so far, I never expected help like this so quickly!

    Hard to follow you when you're creating new threads on the same topic...
    First of all - don't use Motion to crop - that's easily done in FCP - if you want to follow the edges of the head, use the Mask tool in Motion.
    Second, there's a video tutorial for using the tracking tools in Motion here:
    http://motionsmarts.com/
    Patrick

  • How do I send an Image over a socket ?

    I'm trying to get the output from my webcam and send that data out to a socket. Now the output from the webcam is running I'm just not sure how to send it out over the socket.
    Server.java
    import java.io.*;
    import java.net.*;
    public class Server {
       public static void main(String args[]) {
         ServerSocket serverSocket = null;
         boolean listening = true;
         try {
         serverSocket = new ServerSocket(1354);
         System.out.println("Listening for Connections...");
         } catch (IOException drr) {
         System.out.println("Error Listening :" + drr);
         System.exit(-1);
         try {
         while(listening)
         new ServerThread(serverSocket.accept()).start();
         } catch (IOException er) {
         System.out.println("Error Creating connection:" + er);
         try {
           serverSocket.close();
         } catch (IOException err) {
         System.out.println("Error Closing:" + err);
    }When a connection is made it will start the webcam and send the image.
    ServerThread.java
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    public class ServerThread extends Thread {
        public static Player player = null;
        public CaptureDeviceInfo di = null;
        public MediaLocator ml = null;
        public JButton capture = null;
        public Buffer buf = null;
        public Image img = null;
        public VideoFormat vf = null;
        public BufferToImage btoi = null;
        public ImagePanel imgpanel = null;
        private Socket socket = null;
        Image blah;
        PrintWriter out = null;
        public ServerThread(Socket socket) {
         super("ServerThread");
         this.socket = socket;
        public void run() {
         try {
             out = new PrintWriter(socket.getOutputStream(), true);        
             imgpanel = new ImagePanel();
                 String str1 = "vfw:CompUSA PC Camera:0";
                 String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
                 di = CaptureDeviceManager.getDevice(str2);
             ml = new MediaLocator("vfw://0");
                try {
               player = Manager.createRealizedPlayer(ml);
                 } catch (Exception npe) {
               System.out.println("Player Exception:" + npe);
                player.start();
             Component comp;
             if ((comp = player.getVisualComponent()) != null) {
               // Grab a frame
               FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
               buf = fgc.grabFrame();
               btoi = new BufferToImage((VideoFormat) buf.getFormat());
               //Send the image over the socket
               out.println(btoi);
         } catch (IOException e) {
             System.out.println("It bombed:" + e);
        public static void playerclose() {
           player.close();
           player.deallocate();
      class ImagePanel extends Panel {
        public Image myimg = null;
        public ImagePanel() {
        public void setImage(Image img) {
          this.myimg = img;
          repaint();
        public void paint(Graphics g) {
          if (myimg != null) {
            g.drawImage(myimg, 0, 0, this);
      }The output I get from running the server is this:
    BufferedImage@c9131c: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Now how can I turn this into an image If this output is correct?

    HUH?
    I got the one to send the images over the network. I'm now trying to get the exact feed of the webcam and sending that over the network. This is alot more difficult to accomplish but I did see where I messed up my process of sending the images was just having to save the file then open it up put it in a byte array then send that over the network to the client. Once it was at the client i was able to re-construct it and throw it up in the frame. The only problem was lag. So this tells me it would be much more faster if instead of saving the file to send the client and having to reconstruct the image I should just send the webcam feed i used to make the image.
    eh, I guess I didn't need any help.
    Hey no offense or anything but you really have to learn how to spell better.

  • Draw image using paint() only once.

    I am having performance issues with my application. It is creates a graph like data display. The display is static. However each time paint is called the image is re-rendered. I want it only rendered once to improve performance, I tried to do this using the following code:
    public void paint(Graphics g){
              if (alreadyRun) return;
              //super.paint(g);
              alreadyRun = true;
    // draw graphics code
    }Unfortunately the required image appears for a moment then disappears. Is there any way to render the image only once? Also, are there any other performance improving measures I can take? I was thinking of rendering only the part of the image that appears on screen (my graphics display is usually bigger than the actual screen size)

    The common way to deal with performance like this is to draw the graph (or whatever) onto a BufferedImage then have the paint (or paintComponent in Swing) simply draw the image. The single draw image is quite fast and keeps the pixel values persistant across paints. If you already have a single image as the thread title hints, the paint shouldn't create much of a performance hit. The reason you are seeing your image disappear is that any time a window is resized, repacked, moved, covered up, or a multitude of other reasons, it calls paint again, so even with static data, there will be times the paint method is called again, causing your drawing to disappear.

  • Drawing images in JComponent

    Hi,
    I have an application laid out as Figure 1 depicts.
    JFrame
    |
    | JMenuBar
    |-----------------------------------------
    | ------------------JPanel - appPanel
    | |--------------------------------|
    | | ---|------------------ JPanel - displayPanel
    | | | |
    | |----------------|---------------|
    | |-------------------------- JComponent - jcanvas
    |
    | |--------------------------------|
    | | ----|----------------------- JPanel - controlPanel
    | | |
    | |--------------------------------|
    |
    |--------------------------------------------
    Figure 1
    The problem I am having is that:
    theJPanel (appPanel) contains two JPanels (displayPanel and controlPanel) and I am adding a JComponent called JCanvas
    to the displayPanel and I use it to draw images on it of type BufferedImage. Now, the image is displayed without any problem
    but when I resize the application (JFrame) I lose my image. I know the JCanvas (JComponent) is being redrawn because I can
    temporarily see the image but something is overwriting the image. I have set appPanel, displayPanel, controlPanel to opaque
    but I still loose the image.
    Of point maybe, if I access the JMenuBar the image will appear less what part of the menu bar obscures it.
    The appPanel, controlPanel, and displayPanel are created in the IDE. Where as, the JCanvas is a seperate class extending JCompoment
    and it has it own paintComponent method to do the image rendering and is added to the displayPanel when instantiated.
    What I don't understand is why isn't the image staying visible after a frame resize?
    Thanks,
    Bob

    Hopefully this will fit.
    You will have to provide your own image file.
    * SwingPaintDemo2.java
    * Created on Sep 27, 2008, 10:57:22 AM
    * Company: 
    * Copyright: Sep 27, 2008
    * Version:
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    * @author
    public class SwingPaintDemo2 {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        private static void createAndShowGUI() {
            System.out.println("Created GUI on EDT? " +
                SwingUtilities.isEventDispatchThread());
            JFrame f = new JFrame("Swing Paint Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new MyPanel());
            f.pack();
            f.setVisible(true);
    class MyPanel extends JComponent {
        BufferedImage bi;
        File file;
        Dimension d = new Dimension();
        boolean fullScreen = false;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            file = new File("g://java/images/dido_img.jpg");
            try {
                bi = ImageIO.read(file);
            } catch (IOException ex) {
                Logger.getLogger(MyPanel.class.getName()).
                    log(Level.SEVERE, null, ex);
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(350, 350);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) this.getGraphics();
            d = this.getPreferredSize();
            if (d.width == 0 || d.height == 0) {/* error */
            if (!fullScreen) {
                int px = (d.width - bi.getWidth()) / 2;
                int py = (d.height - bi.getHeight()) / 2;
                g2.drawImage(bi, null, px, py);
            } else {
                g2.drawImage(bi, 0, 0, d.width, d.height,
                    0, 0, bi.getWidth(), bi.getHeight(), null);
    }

  • Display an Image Over a Video

    Hello,
    I need to animate an image over an avi file playing. The problem is the image always is behind the file. I am using Swing for this, the JDesktopPane and the RootPane. Any help appreciated.
    Thank you.

    Hi,
    Here is the code but it still seems not to work.
    JDesktopPane layeredPane = new JDesktopPane(){
    public Dimension getPreferredSize() {
    return new Dimension (300,250);
    public Dimension getMinimumSize() {
    return new Dimension (300,250);
    ImageOverlay Image overlay = new ImageOverlay(); // this is a label
    overlay.setBounds(10, 100, 50 , 75);
    overPanel.add(overlay);
    overPanel.setOpaque(false);
    overPanel.setBounds(10, 100, 50 , 75);
    layeredPane.setDoubleBuffered(true);
    getRootPane().setLayeredPane(layeredPane);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    getRootPane().getLayeredPane().add(visualComponent, new Integer(0));
    getRootPane().getLayeredPane().add(overPanel, new Integer(1));
    Thanks.

  • Display text and image over Video Image in applet

    Hi
    I am working in JMF for a video applet.
    I have a doubt ,how we can display text and image over Video Image.
    Is anybody know how we can draw text over Video Image,pls sent a small code how can do it in applet?.
    I can do it in a frame,but it not work in a applet !
    CHT

    it is very much possible in a htmlb:button.
    its same as how you have done it in xhtmlb:toolbarButton
    working code
            <%
      data image type   ref to cl_htmlb_image.
      data: image_string type string.
      create object image.
      image->id = 'IEX'.
      image->src = cl_bsp_mimes=>sap_icon( 'ICON_EXECUTE_OBJECT' ).
      image->tooltip = 'Find the Link'.
      clear image_string.
      image_string = image->IF_BSP_BEE~RENDER_TO_STRING( page_context ).
              %>
              <htmlb:button id     = "EX"
                            text   = "<%= image_string %> Execute"
                            encode = "FALSE"
                            onClick = "EXECUTE"/>
    Regards
    Raja

  • Placing one image over another

    How can I place one image over another image in java?

    Draw the bottom image first and then the top image. You would need to extend JComponent's paintComponent() method.

  • Can one add more than one photo layer to a draw image?

    I cannot seem to find a way to add more than one photo or photo layer to a Draw image, but the Draw page on Adobe seems to imply multiple photos can be added. How might I accomplish this? Thanks for your time.

    Unfortunately, Draw is currently limited to one photo layer, and only one photo within that layer.
    Hope that helps,
    Frank
    Draw Engineering

Maybe you are looking for

  • Is there a way to prevent Mail from loading non system fonts?

    For over a year, and a system OS upgrade, Mail has been taking 7 - 10 minutes to load all the thousands of fonts I have on my computer for graphic design. This started with Snow Leopard on my 2009 Mac Pro (10 GB RAM, 2 TB HDD). At first I didn't know

  • Code generation for business partner

    Hi, all In our scenario we need to assign a unique code to business partner record as soon as it is approved by data manager (in MDM workdlow). This assignment should be automatic. Next incremental number would suffice, but AutoID field can't be used

  • How to upload multiple items of sales order?

    I have extracted open sales order and transferred it to an excel file. Some SO doument has multiple items on one SO. If I will upload that SO document (with multiple items) into a new server, how am I suppose to itemize that this document has multipl

  • Thunderbolt to hdmi not working after mavericks upgrade

    since upgrading macbook pro late 2011 doesn't recognise / see the second display, is there a fix for this or am i missing something?

  • IPhoto is unresponsive-please someone help

    Every time I open my iPhoto the spinning ball comes up for about 20 seconds then this message appears: Your iPhoto library is either in use or has become unreadable. Shut down and restart your computer, then open iPhoto again. If the problem persists