Painting on JInternalFrame

hey,
Recently i discovered the new class of JInternalFrame and after reading the api and make it appear and etc , i want to ask one more critical question.
i add a JInternalFrame inside a JPanel (which isn't recommended but it was too late to change :\ ). inside that JInternalFrame i wanted to appear some pictures and text. Something that normal painting on JFrame or on JPanel would work. however after overriding paintComponent(Graphics g), it still refuses to show any kind of graphics "life signs".
Thanks in advance,
Aviv Avitan

i add a JInternalFrame inside a JPanel (which isn't recommended but it was too late to change :\ ). It's never too late to change.
I really require help, please don't ignore me. You only posted your question an hour ago. Don't be so impatient. Are we allowed to get some sleep?
Internal frames contain a content pane which is opaque, so the content pane paints over top of the custom painting. Make you content pane transparent:
((JPanel)internalFrame.getContentPane()).setOpaque(false);Or, do your custom painting on a JPanel and then set the panel as the content pane for the internal frame.

Similar Messages

  • Who paints the background of JInternalFrame

    Hello all,
    Im new to Swing / plaf, and I have a probably simple question.
    Im trying to make an internal frame that has rounded corners. Therefore I do not want the background color to fill the entire background. Actually I'd like to paint the background myself.
    I have extended and installed my own BasicInternalFrameUI. In installUI(JComponent c) I call c.setOpaque(false). And would now expect to be able to control the painting of the background by overriding BasicInternalFrameUI.paint :
    public void paint(Graphics g, JComponent c) {
    g.setColor(Color.black);
    g.fillRoundRect(0,0, c.getWidth(),c.getHeight(),10,10);
    (Disregard the fact that I paint on top of the title too - this example is only to keep it simple)
    But the JInternalFrame shows it's background color, and not my rect.
    It seems like the only way I can change the painting of the JInternalFrame is by overriding JInternalFrame.paint :
    public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.blue);
    g.fillRoundRect(0,0, getWidth(), getHeight(),10,10);
    But that's not really look&feel...
    Could someone please enlighten me? How do I paint the background of an JInternalFrame the proper way?

    Hello all,
    Im new to Swing / plaf, and I have a probably simple question.
    Im trying to make an internal frame that has rounded corners. Therefore I do not want the background color to fill the entire background. Actually I'd like to paint the background myself.
    I have extended and installed my own BasicInternalFrameUI. In installUI(JComponent c) I call c.setOpaque(false). And would now expect to be able to control the painting of the background by overriding BasicInternalFrameUI.paint :
    public void paint(Graphics g, JComponent c) {
    g.setColor(Color.black);
    g.fillRoundRect(0,0, c.getWidth(),c.getHeight(),10,10);
    (Disregard the fact that I paint on top of the title too - this example is only to keep it simple)
    But the JInternalFrame shows it's background color, and not my rect.
    It seems like the only way I can change the painting of the JInternalFrame is by overriding JInternalFrame.paint :
    public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.blue);
    g.fillRoundRect(0,0, getWidth(), getHeight(),10,10);
    But that's not really look&feel...
    Could someone please enlighten me? How do I paint the background of an JInternalFrame the proper way?

  • How to paint image in the JInternalFrame Urgent plz

    sir i want to draw a image on the back side of the JInternalFrame
    how can i do
    I do this job by using the following code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class MyInternalFrame extends JInternalFrame
    MyButtonPanel2 panel=new MyButtonPanel2();
    public static JPanel p=new JPanel();
    ImageIcon img=new ImageIcon("images/beach.jpg");
    JLabel backlabel;
    public static int w=376,h=50;
    MyInternalFrame(int width,int height,String str)
    setOpaque(false);
    this.setIconifiable(true);
    this.setSize(width,height);
    this.setTitle(str);
    this.setFrameIcon(new ImageIcon("images/smileyr.gif"));
    setMinimumSize(new Dimension(width,height));
    setPreferredSize(new Dimension(width,height));
    this.getContentPane().setLayout(null);
    panel.setBounds((width/2)-188,height-84,w,h);
    p.setLayout(null);
    int imgwidth=img.getIconWidth();
    int imgheight=img.getIconHeight();
    if((imgwidth<this.getWidth()) || (imgwidth>this.getWidth()))
    imgwidth=this.getWidth();
    if((imgheight<this.getHeight()) || (imgheight>this.getHeight()))
    imgheight=this.getHeight();
    backlabel=new JLabel(img);
    backlabel.setBounds(0,0,imgwidth,imgheight);
    p.add(backlabel,new Integer(Integer.MIN_VALUE));
    p.setBounds(0,0,width,height);
    this.getContentPane().add(panel,new Integer(Integer.MAX_VALUE));
    this.getContentPane().add(p);
    setVisible(true);
    but when i add another panel in the object p the component of another
    panel does not apper like this
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class companypanel extends MyInternalFrame
    LimitTextF nametxt=new LimitTextF(30,50,24);
    MyLabel name=new MyLabel("Company Name");
    LimitTextF codetxt=new LimitTextF(4,50,24);
    MyLabel code=new MyLabel("Company Code");
    companypanel(int width,int height,String str)
    super(width,height,str);
    name.setBounds(10,20,100,25);
    nametxt.setBounds(140,20,80,25);
    super.p.add(name);super.p.add(nametxt);
    plz tell me how can i do?

    These links will help.
    http://java.sun.com/products/jfc/tsc/articles/swing2d/
    http://java.sun.com/j2se/1.4.2/docs/guide/2d/spec/j2d-awt.html
    http://forum.java.sun.com/thread.jsp?forum=31&thread=409047
    rykk

  • Problem in Painting in JDesktopPane

    Hi
    Here is the code for my class:
    public class DiagramPane extends JDesktopPane{
    public DiagramPane() {
    setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    public void paint(Graphics g){
    super.paint(g);
    int cmpCount=getComponentCount();
    if(cmpCount>1){
    for(int i=0;i<cmpCount-1;i++){
    Component cmp1=getComponent(i);
    Component cmp2=getComponent(i+1);
    g.drawLine(cmp1.getX(),cmp1.getY(),cmp2.getX(),cmp2.getY());
    public static void main(String[] s){
    JFrame f=new JFrame();
    DiagramPane dgrPane= new DiagramPane();
    JScrollPane scr=new JScrollPane(dgrPane);
    JInternalFrame lst1=new JInternalFrame("Frame1");
    JInternalFrame lst2=new JInternalFrame("Frame2");
    lst1.setBounds(150,150,100,100);
    lst2.setBounds(300,300,100,100);
    lst1.show();
    lst2.show();
    f.getContentPane().add(scr);
    dgrPane.add(lst1);
    dgrPane.add(lst2);
    f.setSize(400,400);
    f.show();
    Run this code and try to move any of the two InternalFrames. The lines need to be repainted accurately but this doesn't happen. This happens due to background filling of dirty region in JLayeredPane paint method. Can anyone tell me, what I should do so as to make these lines repaint properly. Lines are not in dirty region.
    Thanks in advance.
    Anil.

    You need your own DesktopManager that triggers a repaint after dragging ends, like:
    class MyDesktopManager extends DefaultDesktopManager {
    public void endDraggingFrame(JComponent comp) {
         super.endDraggingFrame(comp);
         repaint();
    then use it in your custom DesktopPane
    public DiagramPane() {
    setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    setDesktopManager(new MyDesktopManager());
    Greetings
    Jeanette

  • Getting clipped graphics when painting in response to mouse event

    Can anyone tell me how to get a graphics object with the clipping region set appropriately when painting in response to a mouse action
    rather than in paintComponent where the system provides the Graphics object?
    The issue is that a graphical component I have written needs to repaint parts of itself in response to mouse actions. I have been getting the Graphics object by calling getGraphics on the component (based on JPanel) and using that to do the required painting. This works fine as long as there are no lightweight Swing objects in front of my component, but as I recently discovered when I added this component to a couple of JInternalFrames, mouse-triggered painting can paint on the other JInternalFrame.
    The example code below illustrates the problem.
    Thanks in advance
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    * This class illustrates a problem I am having with a graphical component I have
    * written that works fine when placed in a JFrame, but when placed inside a JInternalFrame,
    * can draw outside the bounds of the JInternalFrame.
    * The real component contains many sub-objects, and users can select an individual sub-object,
    * and trigger actions specific to that sub-object. To aid in sub-object selection,
    * when the mouse pointer is over a sub-object, the color of the object is changed to
    * a highlight color. This is where the problem of drawing outside the JInternalFrame occurs.
    * I am pretty sure that the reason the drawing can occur outside the bounds of the
    * JInternalFrame is that the graphics context used for the highlighting action does not
    * have the clipping region set. Unlike in paintComponent where the system provides the
    * Graphics object with the clipping region set appropriately, painting of individual
    * sub-objects in response to a MouseEvent is done using a call to getGraphics on the
    * component. This has the clipping region set to the dimensions of the JPanel.
    * This example creates two overlapping JInternalFrames. Inside each is a simple component
    * based on a JPanel. The component draws a single filled circle which corresponds to
    * one of the sub-objects in the real component. When the mouse pointer is over a circle,
    * the color changes from gray to red. Where the circle overlaps the other JInternalFrame,
    * the circle will paint over that frame.
    public class GraphicsProblemDemo extends JFrame {
        private static final int APP_FRAME_SIZE = 400;
        public GraphicsProblemDemo()
            JDesktopPane desktop = new JDesktopPane();
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            getContentPane().setLayout( new BorderLayout() );
            getContentPane().add( desktop, BorderLayout.CENTER );
            setSize( APP_FRAME_SIZE, APP_FRAME_SIZE );
            setVisible( true );
            // Create two JInternalFrames, each with a single component that
            // draws a filled circle.
            JInternalFrame frame = createInternalFrame( 0, 0 );
            frame.setVisible( true );
            desktop.add( frame );
            frame = createInternalFrame( 200, 200 );
            frame.setVisible( true );
            desktop.add( frame );
        public JInternalFrame createInternalFrame( int left, int top )
            JInternalFrame frame = new JInternalFrame( "", true, true, true, true );
            int INTERNAL_FRAME_SIZE = 300;
            frame.setBounds( left, top, INTERNAL_FRAME_SIZE, INTERNAL_FRAME_SIZE );
            myComponent shape = new myComponent();
            frame.add( shape );
            return frame;
         * This component simulates the more complex component that I am trying to debug.
         * The real component contains many sub-objects and is expensive to render.
         * Individual sub-objects are selectable within the component, and to indicate to the
         * user that the mouse is positioned over a sub-object, the sub-object color is changed.
         * Because it is expensive to render the component completely, the MouseMotionListener
         * does not call repaint on the component. Instead, it gets the graphics context,
         * sets the color, and renders the component under the mouse pointer.
        class myComponent extends JPanel implements MouseMotionListener {
            private Ellipse2D.Double subObject = new Ellipse2D.Double( 10, 10, 200, 200 );
            private Color unselectedColor = Color.LIGHT_GRAY;
            private Color selectedColor = Color.RED;
            private Color renderColor = unselectedColor;
            public myComponent()
                addMouseMotionListener(this);
            // Painting is fine when this method is called by the system.
            public void paintComponent( Graphics g )
                super.paintComponent( g );
                // In the real component, many objects would be rendered here, but
                // this example component has only a single sub-object.
                renderMySingleSubObject( g );
            // But when this method is called by my mouse listener using the
            // graphics context from the containing JPanel, the circle is rendered on top
            // of the other JInternalFrame.
            private void renderMySingleSubObject( Graphics g )
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor( renderColor );
                g2d.fill( subObject );
             * If the mouse pointer is over my single sub-object, then change
             * the color from gray to red and render  the sub-object.
             * @param e The MouseEvent
            public void mouseMoved( MouseEvent e )
                if( subObject.contains( e.getX(), e.getY() ) )
                    renderColor = selectedColor;
                else
                    renderColor = unselectedColor;
                Graphics g = myComponent.this.getGraphics();
                // This graphics context does not have the clipping region set
                renderMySingleSubObject( g );
            public void mouseDragged( MouseEvent e )
        public static void main( String[] args )
            new GraphicsProblemDemo();
    }

    Checking the method description for the 'getGraphics' method in the Component api the first sentence says "Creates a graphics context for this component." Emphasize 'creates'. You can demonstrate the difference by printing the Graphics context g in each case. Checking for the clip in each returns null for the 'getGraphics' call.
                super.paintComponent( g );
                // In the real component, many objects would be rendered here, but
                // this example component has only a single sub-object.
                renderMySingleSubObject( g );
                System.out.println("paintComponent g = " + g);
                System.out.println("paintComponent g clip = " + g.getClip().toString());
                Graphics g = myComponent.this.getGraphics();
                System.out.println("getGraphics g = " + g);
                // NullPointer here...
                System.out.println("getGraphics g clip = " + g.getClip().toString());Suggests that 'getGraphics' might not be the way. You could, of course, check all the iframes and find out how much of the moused-over ellipse is visible and put together something to send along for the re-rendering...
    Here's another possibility. The repaint code doesn't recover well for mouse exits of the lower iframe into the upper but it will give an idea about economy and control.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    public class GPD extends JFrame {
        private static final int APP_FRAME_SIZE = 400;
        public GPD()
            JDesktopPane desktop = new JDesktopPane();
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            getContentPane().setLayout( new BorderLayout() );
            getContentPane().add( desktop, BorderLayout.CENTER );
            setSize( APP_FRAME_SIZE, APP_FRAME_SIZE );
            setVisible( true );
            // Create two JInternalFrames, each with a single component that
            // draws a filled circle.
            JInternalFrame frame = createInternalFrame( 0, 0 );
            frame.setVisible( true );
            desktop.add( frame );
            frame = createInternalFrame( 200, 200 );
            frame.setVisible( true );
            desktop.add( frame );
        public JInternalFrame createInternalFrame( int left, int top )
            JInternalFrame frame = new JInternalFrame( "", true, true, true, true );
            int INTERNAL_FRAME_SIZE = 300;
            frame.setBounds( left, top, INTERNAL_FRAME_SIZE, INTERNAL_FRAME_SIZE );
            myComponent shape = new myComponent();
            frame.add( shape );
            return frame;
        class myComponent extends JPanel implements MouseMotionListener {
            private Ellipse2D.Double subObject = new Ellipse2D.Double( 10, 10, 200, 200 );
            private Color unselectedColor = Color.LIGHT_GRAY;
            private Color selectedColor = Color.RED;
            private Color renderColor = unselectedColor;
            int count = 0;
            public myComponent()
                addMouseMotionListener(this);
            // Painting is fine when this method is called by the system.
            public void paintComponent( Graphics g )
                super.paintComponent( g );
                g.setColor( renderColor );
                ((Graphics2D)g).fill( subObject );
             * If the mouse pointer is over my single sub-object, then change
             * the color from gray to red and render  the sub-object.
             * @param e The MouseEvent
            public void mouseMoved( MouseEvent e )
                boolean colorHasChanged = false;
                if( subObject.contains( e.getX(), e.getY() ) )
                    if( renderColor == unselectedColor )
                        renderColor = selectedColor;
                        colorHasChanged = true;
                else if( renderColor == selectedColor )
                    renderColor = unselectedColor;
                    colorHasChanged = true;
                if( colorHasChanged )
                    System.out.println("repainting " + count++);
                    repaint();
            public void mouseDragged(MouseEvent e) { }
        public static void main( String[] args )
            new GPD();
    }

  • A question on JInternalFrame of Swing. Let see the code

    Hello everybody,
    I am setting up a Frame that contains 2 JInternalFrames in its desktopPane. The first JInternalFrame is to show the map. The second one have some check box. What I wanna do is, when I check the CheckBox in the second JInternalFrame, after getting the result from Database, it show the result on Map. The result will be some red ellipses on the first JInternalFrame.
    The code work well with Database. But I really need your help to do with the event on InternalFrame
    Thanks in advance !
    Quin,
    Here is the code of the main Frame:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.beans.*;
    public class MapLocator
         public static void main(String [] args)
              JFrame frame = new DesktopFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    Create a desktop frames that contains internal frame
    class DesktopFrame extends JFrame implements ActionListener
         public DesktopFrame()
              super("Map Locator v.1.0.0");
              this.setSize(new Dimension(WIDTH,HEIGHT));
              desktop = new JDesktopPane();
              this.setContentPane(desktop);
              this.createInternalFrame(
                   new mapPanel(),"Ban do Thanh pho Ho Chi Minh",0,0,480,515);
              this.createInternalFrame(
                   new commandPanel(),"Chu thich va tim kiem",480,0,320,515);
    Create an internal frame on the desktop.
    @param c the component to display in the internal frame
    @param t the title ofthe internal frame.
         public void createInternalFrame(JPanel c, String t,int ifx, int ify, int ifwidth, int ifheight)
                 final JInternalFrame iframe = new JInternalFrame(t,
                 true//resizeable
                 ,true//closable
                 ,true//maximizable
                 ,true//iconifiable
                 iframe.getContentPane().add(c);
                 desktop.add(iframe);
                 iframe.setFrameIcon(new ImageIcon("new.gif"));
                 //add listener to confirm frame closing
                 iframe.addVetoableChangeListener(new VetoableChangeListener()
                      public void vetoableChange(PropertyChangeEvent event)
                           throws PropertyVetoException
                           String name = event.getPropertyName();
                           Object value = event.getNewValue();
                           //we only want to check attempts to close a frame
                           if(name.equals("closed") && value.equals(Boolean.TRUE))
                                //ask user if it is ok to close
                                int result =
                      JOptionPane.showInternalConfirmDialog(iframe,"OK to close");
                                //if the user doesn't agree, veto the close
                                if(result != JOptionPane.YES_OPTION)
                      throw new PropertyVetoException("User cancel the close",event);
                 iframe.setVisible(true);
                 iframe.setLocation(ifx,ify);
                 iframe.setSize(new Dimension (ifwidth, ifheight));
         private static final int WIDTH = 800;
         private static final int HEIGHT = 600;
         private JDesktopPane desktop;
         private int nextFrameX;
           private int nextFrameY;
            private int frameDistance;
         private JMenuBar menuBar;
         private JMenu fileMenu, viewMenu, searchMenu, windowMenu, helpMenu;
         private JRadioButtonMenuItem javalaf, liquidlaf, motiflaf, windowlaf, threedlaf;
    }Below is the code of first JInternalFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import java.util.*;
    import com.sun.image.codec.jpeg.*;
    Create a canvas that show a map
    public class mapPanel extends JPanel
         implements MouseMotionListener, MouseListener
         public mapPanel()
              addMouseMotionListener(this);
              addMouseListener(this);
    Unbarrier the comment below to see how the map model work
    //Unbarrier this to see -->
             try
                InputStream in = getClass().getResourceAsStream(nameOfMap);
                JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                mImage = decoder.decodeAsBufferedImage();
                in.close();//Close dong nhap
              catch(ImageFormatException ie)
              { System.out.println ("Error on formating image");}
              catch(IOException ioe)
              { System.out.println ("Error on input/ouput image");}
              catch(Exception e){}
    Connect to database
              connDB();
              String addQuery = "";
              try
              Get the relation amongs points
                   int idStart = 0;
                   int idEnd = 0;
                   addQuery ="SELECT IDStart, IDEnd FROM 2Diem";
                   rs = stmt.executeQuery(addQuery);
                   int incre = 0;
                   while(rs.next())
                        idStart = rs.getInt(1);
                        Rel.add(incre, new Integer(idStart));
                        incre ++;
                        idEnd = rs.getInt(2);
                        Rel.add(incre, new Integer(idEnd));
                        incre ++;
         Load the Coordination of the points to hash table
                   int idPoint = 0;
                   int XP = 0;
                   int YP = 0;
                   addQuery ="SELECT IDDiem, CoorX, CoorY FROM Diem";
                   rs = stmt.executeQuery(addQuery);     
                   while(rs.next())
                        idPoint = rs.getInt(1);
                        XP = rs.getInt(2);
                        YP = rs.getInt(3);
                        hashX.put(new Integer(idPoint), new Integer(XP));
                        hashY.put(new Integer(idPoint), new Integer(YP));
         Create Points to draw the Line
                   line = new Line2D[(Rel.size())/2];
                   for(int i = 0, k = 0; i < Rel.size();i++, k = k+2)
                        X1 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y1 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        i++;
                        X2 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y2 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        line[k/2] = new Line2D.Double(X1,Y1,X2,Y2);
              catch(SQLException sqle){}
         private Hashtable hashX = new Hashtable();
         private Hashtable hashY = new Hashtable();
         private Vector Rel = new Vector(100,10);
         private Vector vecBackX = new Vector(10,2);
         private Vector vecBackY = new Vector(10,2);
         private int X1 = 0, X2 = 0, Y1 = 0, Y2 = 0;
         Draw the image to show
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(
                   RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
        //     g2.drawImage(mImage,0,0,null);
        Paint the background with light Gray
              g2.setPaint(Color.lightGray);
              g2.fill(new Rectangle2D.Double(0,0,480,480));          
             fillBack(g2);
        Draw the street with its border is white, its background is orange
             g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(14,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
              g2.setPaint(Color.orange);
              g2.setStroke(new BasicStroke(10,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
         Draw the grid on map
              g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(1));
              drawGrid(g2);
              if(point != null)
                   g2.setPaint(Color.red);
                   g2.fillOval(point.x - 3, point.y - 3, 7, 7);
    Draw the Background with tree and water
    @param g2 the Graphics2D that used to draw shapes
         private void fillBack(Graphics2D g2)
              Draw the background for map
              try
                   int BackX = 0;
                   int BackY = 0;
                   int incre = 0;
                   backGround = new GeneralPath[3];
                   for(int idBack = 1; idBack <= 3; idBack++)
    Since we use the vector for each background(tree / water), we have to
    refresh the vector before it can add new path inside
                        vecBackX.clear();
                        vecBackY.clear();
                        String addQuery = "SELECT CoorX, CoorY FROM BackCoor WHERE "
                        + " IDBack =" + idBack;
                        rs = stmt.executeQuery(addQuery);
                        while(rs.next())
                             BackX = rs.getInt(1);
                             BackY = rs.getInt(2);
    This will take the point into vector
                             vecBackX.add(incre,new Integer(BackX));
                             vecBackY.add(incre,new Integer(BackY));
                             incre++;
    Design the shapes of path
                             backGround[(idBack - 1)] =
                                  new GeneralPath(GeneralPath.WIND_EVEN_ODD);
                             backGround[(idBack - 1)].moveTo(
                                  Integer.parseInt(""+vecBackX.elementAt(0)),
                                  Integer.parseInt(""+vecBackY.elementAt(0)));
                             for(int i = 1; i < vecBackX.size(); i++)
                                  backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(i)),
                                       Integer.parseInt(""+vecBackY.elementAt(i)));
                             backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(0)),
                                       Integer.parseInt(""+vecBackY.elementAt(0)));
                             backGround[(idBack - 1)].closePath();
    Here we have 3 Path that represented to tree and water
    The first and second one is tree.
    The last one is water.
    Draw the path now
                             if(idBack == 3)
                                  g2.setPaint(Color.cyan);
                                  g2.fill(backGround[(idBack - 1)]);
                             else
                                  g2.setPaint(Color.green);
                                  g2.fill(backGround[(idBack - 1)]);
                             incre = 0;
              catch(SQLException sqle)
                   System.out.println ("Khong ve duoc back ground");
    Create the grid on map
    @param g2 the Graphics2D that used to draw shapes
         private void drawGrid(Graphics2D g2)
              try
                 String Query =
                 "SELECT * FROM Grid";
                 rs = stmt.executeQuery(Query);
                 GridX = new Vector(100,2);
                 GridY = new Vector(100,2);
                 GridW = new Vector(100,2);
                 GridH = new Vector(100,2);
                 int incr = 0;
                 while(rs.next())
                      gridX = rs.getInt(2);
                      gridY = rs.getInt(3);
                      gridW = rs.getInt(4);
                      gridH = rs.getInt(5);
                      GridX.add(incr, new Integer(gridX));
                      GridY.add(incr, new Integer(gridY));
                      GridW.add(incr, new Integer(gridW));
                      GridH.add(incr, new Integer(gridH));
                      incr ++;
                 rec = new Rectangle2D.Double[GridX.size()];
                 for(int i = 0; i < GridX.size(); i++)
                      gridX = Integer.parseInt(""+GridX.elementAt(i));
                      gridY = Integer.parseInt(""+GridY.elementAt(i));
                      gridW = Integer.parseInt(""+GridW.elementAt(i));
                      gridH = Integer.parseInt(""+GridH.elementAt(i));
                      rec[i] = new Rectangle2D.Double(gridX, gridY, gridW, gridH);
                      g2.draw(rec);
    catch(SQLException sqle){}
    private Vector GridX, GridY, GridW, GridH;
    private int gridX = 0, gridY = 0, gridW = 0, gridH = 0;
    Fill the point
         public void placePoint(Graphics2D g2,Point p)
              g2.setPaint(Color.red);
              g2.fill(new Ellipse2D.Double(p.x - 3, p.y - 3, 7,7));
    Create connection to Database
         public void connDB()
              System.out.println ("Connecting to Database");
              String fileName = "Pro.mdb";
              String data = "jdbc:odbc:Driver={Microsoft Access Driver " +
         "(*.mdb)};DBQ=" + fileName + ";DriverID=22";
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection(data,"","");
                   stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
              catch(ClassNotFoundException ce)
              { System.out.println ("Khong tim thay Driver"); }
              catch(SQLException sqle)
              { System.out.println ("Loi SQL trong khi Connect"); }
              Statement stmt = null;
              ResultSet rs = null;
              Connection conn = null;     
    This one is the model map to draw
         private String nameOfMap = "map.jpg";
         private BufferedImage mImage;
    Initialize the path and shapes to draw
         private Line2D line[];
         private Rectangle2D.Double rec[];
         private GeneralPath backGround[];
         private Point point;
         private int changeColor = 0;
    The last one is:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    public class commandPanel extends JPanel implements ActionListener
    Initial check box
         JCheckBox uyBanNhanDan = new JCheckBox();
         JCheckBox nganHang = new JCheckBox();
         JCheckBox buuDien = new JCheckBox();     
         JCheckBox khachSan = new JCheckBox();     
         JCheckBox benhVien = new JCheckBox();          
         JCheckBox cho = new JCheckBox();     
         JCheckBox nhaHat = new JCheckBox();     
         JCheckBox daiHoc = new JCheckBox();     
         JCheckBox thuvien = new JCheckBox();     
         JCheckBox nhaTho = new JCheckBox();     
         public commandPanel()
              this.setLayout(new BorderLayout());
              this.setBorder(BorderFactory.createCompoundBorder(
                          BorderFactory.createTitledBorder("***Chu dan***"),
                          BorderFactory.createEmptyBorder(5,5,5,5)));
    Create the combobox to show information
              uyBanNhanDan.setText("Uy Ban ND Quan");
              nganHang.setText("Ngan Hang");
              buuDien.setText("Buu Dien");
              khachSan.setText("Khach San");
              benhVien.setText("Benh Vien");
              cho.setText("Cho - Mua Sam");
              nhaHat.setText("Nha Hat");
              daiHoc.setText("Dai Hoc - Dao Tao");
              thuvien.setText("Thu Vien - Nha Sach");
              nhaTho.setText("Nha Tho - Chua");
              uyBanNhanDan.addActionListener(this);
              nganHang.addActionListener(this);
              buuDien.addActionListener(this);
              khachSan.addActionListener(this);
              benhVien.addActionListener(this);
              cho.addActionListener(this);
              nhaHat.addActionListener(this);
              daiHoc.addActionListener(this);
              thuvien.addActionListener(this);
              nhaTho.addActionListener(this);
              uyBanNhanDan.setActionCommand("1");
              nganHang.setActionCommand("2");
              buuDien.setActionCommand("3");
              khachSan.setActionCommand("4");
              benhVien.setActionCommand("5");
              cho.setActionCommand("6");
              nhaHat.setActionCommand("7");
              daiHoc.setActionCommand("8");
              thuvien.setActionCommand("10");
              nhaTho.setActionCommand("11");
              JPanel secP = new JPanel();
              secP.setLayout(new GridLayout(5,2));
              secP.add(uyBanNhanDan);
              secP.add(nganHang);
              secP.add(buuDien);
              secP.add(khachSan);
              secP.add(benhVien);
              secP.add(cho);
              secP.add(nhaHat);
              secP.add(daiHoc);
              secP.add(thuvien);
              secP.add(nhaTho);
              this.add(secP,BorderLayout.NORTH);
         public void actionPerformed(ActionEvent event)
              int x = 0;
              int y = 0;
              try
                   mapPanel mp = new mapPanel();
                   int idDiaDanh = 0;
                   if(event.getActionCommand() == "1")
                        idDiaDanh = 1;
                   String Query =
                   "SELECT CoorX, CoorY FROM MoTa WHERE IDDiaDanh =" + idDiaDanh;
                   mp.rs = mp.stmt.executeQuery(Query);
                   while(mp.rs.next())
    /*I have problem here*/
    /*Process the event for me*/          x = mp.rs.getInt(1);
                        y = mp.rs.getInt(2);
                        Graphics g2 = mp.getGraphics();
                        mp.paintComponents(g2);
                             g2.setPaint(Color.red);
                             g2.fill(new Ellipse2D.Double(x - 3, y - 3, 7, 7));     
              catch(SQLException sqle){}

    Strings are Objects.
    String[] strings = new String[3];
    String[0]="abcde";Right here, you are initializing the String array, and the String at index 0.
    JButton[] buttons = new JButton[2];
    buttons[0].setText("abcde");Right here, you are initializing the JButton array, but not any of the JButtons in the array. You then try to use the setText() method on a null JButton.

  • JInternalframe always on top instead of overlapping

    Hello guys,
    I have some JInternalFrames but one window paints its content above all, even overlapping frames. The code looks like this:
    package visnav.bachelor.gallery;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.ScrollPane;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import java.lang.Math;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import javax.swing.border.EtchedBorder;
    import visnav.bachelor.DataLoader;
    import visnav.bachelor.preview.PreviewMap_Ext;
    import visnav.common.Config;
    import visnav.common.DBListener;
    import visnav.common.Options;
    import visnav.common.Photo;
    * The class Gallery adds a window in which all selected Photos (=their
    * thumbnails) can be seen.
    * @author Florian Kratschmann
    public class Gallery extends ScrollPane implements DBListener {
         private static Vector<Photo> selectedPhotos;
         private static Gallery instance;
         public JPanel content = new JPanel(new ModifiedFlowLayout(
                   ModifiedFlowLayout.LEFT, 6, 6));
         public String filename = "";
          * Constructor which creates a new Gallery object.
         public Gallery() {
              selectedPhotos = DataLoader.getInstance().getSelectedPhotos();
              this.updateGUI(selectedPhotos);
         public static Gallery getInstance() {
              if (instance == null)
                   instance = new Gallery();
              return instance;
         public void collectionChanged() {
              selectedPhotos = DataLoader.getInstance().getSelectedPhotos();
              this.updateGUI(selectedPhotos);
         public void selectionChanged() {
              selectedPhotos = DataLoader.getInstance().getSelectedPhotos();
              this.updateGUI(selectedPhotos);
         public void valueChanged() {
              selectedPhotos = DataLoader.getInstance().getSelectedPhotos();
              this.updateGUI(selectedPhotos);
         public void updateGUI(Vector<Photo> data) {
              content.removeAll();
              removeAll();
              for (int i = 0; selectedPhotos.size() > i; i++) {
                   filename = Gallery_Ext.getFileName(selectedPhotos.get(i)
                             .getFileLocation());
                   final int j = i;
                   ImageIcon icon = (new ImageIcon(selectedPhotos.get(i)
                             .getThumbLocation()));
                   if (filename.length() > 15) {
                        filename = filename.substring(0, 15) + "...";
                   JButton thumb = new JButton("<html><p align=\"center\">" + filename
                             + "<br>[" + (i + 1) + "/" + selectedPhotos.size()
                             + "]<br></p></html>", icon);
                   thumb.setContentAreaFilled(false);
                   thumb.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             Gallery_Ext.openMIME(selectedPhotos.get(j)
                                       .getFileLocation());
                   thumb.setVerticalTextPosition(JLabel.BOTTOM);
                   thumb.setHorizontalTextPosition(JLabel.CENTER);
                   thumb.setBorder(new EtchedBorder());
                   thumb.setPreferredSize(new Dimension(140, 140));
                   content.add(thumb);
              add(content);
          * A modified version of FlowLayout that allows containers using this Layout
          * to behave in a reasonable manner when placed inside a JScrollPane
          * Workaround made to fit size of screen on first updateGUI firing
          * @author Babu Kalakrishnan
          * @author Florian Kratschmann
         public class ModifiedFlowLayout extends FlowLayout {
              public ModifiedFlowLayout() {
                   super();
              public ModifiedFlowLayout(int align) {
                   super(align);
              public ModifiedFlowLayout(int align, int hgap, int vgap) {
                   super(align, hgap, vgap);
              public Dimension minimumLayoutSize(Container target) {
                   return computeSize(target, false);
              public Dimension preferredLayoutSize(Container target) {
                   return computeSize(target, true);
              private Dimension computeSize(Container target, boolean minimum) {
                   synchronized (target.getTreeLock()) {
                        int hgap = getHgap();
                        int vgap = getVgap();
                        int w = target.getWidth();
                        if (w == 0) {
                             Dimension size = new Dimension(0, 0);
                             int noOfTn = selectedPhotos.size();
                             try {
                                  size = (Config.getDimension("InternalFrameSize4",
                                            new Dimension(0, 0)));
                                                 if (size.width==0){size.setSize(300, 200);}
                                  int noOfRows = (int) Math.ceil(size.width / 140);
                                  int heightNeeded = (int) ((noOfTn*1.25 / noOfRows) * 140);
                                  size.setSize(140, heightNeeded);
                             } catch (Exception ex) {
                                  ex.printStackTrace();
                                  int peter = 2;
                                  int heightNeeded = ((noOfTn / peter) * 280)+140;
                                  size.setSize(140, heightNeeded + 100);                    
                             return size;
                        } else {
                             // w = Integer.MAX_VALUE;
                             Insets insets = target.getInsets();
                             if (insets == null)
                                  insets = new Insets(0, 0, 0, 0);
                             int reqdWidth = 0;
                             int maxwidth = w - (insets.left + insets.right + hgap * 2);
                             int n = target.getComponentCount();
                             int x = 0;
                             int y = insets.top;
                             int rowHeight = 0;
                             for (int i = 0; i < n; i++) {
                                  Component c = target.getComponent(i);
                                  if (c.isVisible()) {
                                       Dimension d = minimum ? c.getMinimumSize() : c
                                                 .getPreferredSize();
                                       if ((x == 0) || ((x + d.width) <= maxwidth)) {
                                            if (x > 0) {
                                                 x += hgap;
                                            x += d.width;
                                            rowHeight = Math.max(rowHeight, d.height);
                                       } else {
                                            x = d.width;
                                            y += vgap + rowHeight;
                                            rowHeight = d.height;
                                       reqdWidth = Math.max(reqdWidth, x);
                             y += rowHeight;
                             return new Dimension(
                                       reqdWidth + insets.left + insets.right, (int) (y*1.2));
                             // return new Dimension(120, 300);
    }Any idea why it's content is always on top?
    Cheers,
    Flo

    As the title I can have inside a JDesktopPane some JinternalFrame "always on top" compared to one that makes the background?You might get better help by explaining what you want to achieve, rather than how you want to achieve it.
    You can do custom painting in a JDesktopPane, you know.
    db

  • Component resize, paint and AffineTransform

    Hello,
    I am resizing a JInternalFrame that contains a JPanel.
    When I call:
    MyJPanel.repaint();The paint function gets the dimensions of the JPanel
    using getWidth() and getHeight(), once, at the start of the
    paint function. The function then proceeds to plot some lines and
    points on a graph. Everything appears to work fine for lines and points (ie: drawOval).
    The function then goes on to draw some text for the axes of the graph. The Y axis
    text plots fine. The X axis text is rotated using AffineTransform and plots intermittently
    with the correct and incorrect position.
    Calling repaint() for the JPanel, without resizing,
    everything renders in the proper place
    via the overridden paint() procedure for that panel.
    When I resize the JInternalFrame, thus causing the
    JPanel to also automatically resize and repaint, the JPanel
    paints all lines and points in the correct locations
    with respect to the bounds of the JPanel. The
    Y axis text, drawn using drawText() plots in the correct place.
    The X axis text then plots in the wrong place after AffineTransform
    positioning in a location that would indicate it is transforming based on the
    coordinate system of the JInternalFrame rather than the JPanel (??).
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
                        Graphics2D g2d=(Graphics2D)g;
                        AffineTransform old_at=((Graphics2D)g).getTransform();
                        AffineTransform at = new AffineTransform(old_at);
                        at.setToTranslation(xoff, yoff);
                        at.rotate((angle_degrees/360.0)*Math.PI*2.0);
                        g2d.setTransform(at);
                        g2d.drawString(text, 0, 0);
                        g2d.setTransform(old_at);
                    }The parameter Graphics g is the Graphics passed from public void MyJPanel.paint(Graphics g) .
    Why would AffineTransform get confused regarding which component the Graphics is coming from?
    More importantly, how can I avoid the problem?
    Thanks,
    P

    >
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform old_at=((Graphics2D)g).getTransform();
    AffineTransform at = new AffineTransform(old_at);
    at.setToTranslation(xoff, yoff);
    at.rotate((angle_degrees/360.0)*Math.PI*2.0);
    g2d.setTransform(at);
    g2d.drawString(text, 0, 0);
    g2d.setTransform(old_at);
    The problem is with the use of at.setToTranslation(xoff, yoff); instead of at.translate(xoff, yoff).
    After changing that the problem cleared up.
    P

  • Multiple Images in JInternalFrames

    Hi,
    I'm trying to open n number of images in a desktop, each in its own JInternalFrame. I've set up an array of bufferedImages which store each required image. I have a class called MYJPanel which paints the image into an internal frame and have set up an array of instances of this class. It successfully opens images but when I go to open more than one, it creates a new internal window with this image as desired, but it also replaces the image in the first internal frame with this new image. I think its got something to with the paintComponent(Graphics g) but I'm not too sure. Here's a sample of the code below:
    public void OpenNewImage()
    openImageCount++;
    panels[openImageCount] = new MyJPanel();
    fileBrowser.setVisible(false);
    c[openImageCount] = new Container();
    frames[openImageCount] = new JInternalFrame("Image " + openImageCount, true, true, true,true);
    c[openImageCount] =frames[openImageCount].getContentPane();
    c[openImageCount].add(panels[openImageCount], BorderLayout.CENTER);
    frames[openImageCount].setOpaque(true);
    frames[openImageCount].setSize(300,200);
    frames[openImageCount].show();
    //To move the second image to the right hand side of the screen
    if (openImageCount == 2)
    frames[openImageCount].setLocation(350,0);
    theDesktop.add(frames[openImageCount]);
    class MyJPanel extends JPanel implements MouseListener, MouseMotionListener
    public MyJPanel()
    // Store chosen image into images array
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    images[openImageCount] =readInImage(filePath);
    public BufferedImage readInImage(String filename) {
                        BufferedImage bimage;
                        // Read in original image
                        Image im = Toolkit.getDefaultToolkit().getImage(filename);
                        try {
         MediaTracker tracker = new MediaTracker(new Component() {});
    tracker.addImage(im, 0);
    tracker.waitForID(0);
                             bimage = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_3BYTE_BGR);
                   Graphics2D big = bimage.createGraphics();
         big.drawImage(im,0,0,null);
                             return(bimage);
    catch ( Exception e ) {
                             System.out.println("Error Reading Image...Check Filename and Extension");
                             return(null);
    public void paintComponent(Graphics g)
    for (int i=1; i<=openImageCount; i++){
    g.drawImage(images,0,0,300,200,this);
    Does anyone know where I'm going wrong?
    Many thanks,
    CG.

    u have to do some custom painting in order to achieve this. override the paintComponent() method in your JButton subclass and write code to display the images in some sequence...
    cheers,
    ram

  • Overwrite paint() menthod

    Hi
    I have one problem with paint() method, i opened the multiple audio files at a time or one by one
    corresponding files are opened( wave forms) in respective internalFrame,
    For that in file open i am creating new instance of JInternal frame and adding the BuildGUI inner class object to the jif contentpane,
    BuildGui class has a panel in that call the SamplingGraph class which extends JPanel.
    SamplingGraph instance is creating in BuildGUI only, and paint() method is in SamplingGraph.
    When ever i open the wave file that is painting fine, but open one more file the the latest file wave form is in both internalframes. how can i stop previous Jinternalframe repaint(),
    i am calling the repaint() method , even any internal frame is moved something paint is called again,
    how can i prevent this
    Is there any way customize paint() method if you know please send me.

    I used paintComponet() but no difference.
    important thing is when ever I open second file the two waves are opening recentopened frame,
    Is there any problem with desktoppane or InternalFrames
    Now I am using two paintComponents serately,
    only recent frame updating.

  • Drop Shadow On JInternalFrame

    I am trying to adapt Romain Guy's DropShadowPanel to make a drop shadow on a JInternalFrame. It seems as the shadow is drawn outside the clip of the frame I have to somehow increase the clip size to see the shadow. It's nearly working but the shadow isn't working when the frame is moved.
    I also tried putting an empty border around the frame and, curiously, that worked in Metal LaF but not Windows which is what I need.
    Can anyone help?
    Note that this class uses Swing labs shadow renderer and GraphicsUtils.
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.LayoutManager;
    import java.awt.image.BufferedImage;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JInternalFrame;
    import org.jdesktop.swingx.graphics.ShadowRenderer;
    import org.jdesktop.swingx.graphics.GraphicsUtilities;
    public class DropShadowInternalFrame extends JInternalFrame implements PropertyChangeListener {
        // angle and distance of the shadow from the original subjects
        private float angle = 45.0f;
        private int distance = 20;
        // cached values for fast painting
        private int distance_x = 0;
        private int distance_y = 0;
        // when shadow member is equaled to null, the factory is asked to
        // re-generated it
        private BufferedImage shadow = null;
        private ShadowRenderer factory = null;
        public DropShadowInternalFrame(String title, boolean resizable, boolean closable,
                boolean maximizable, boolean iconifiable) {
             super(title, resizable, closable, maximizable, iconifiable);
            setShadowFactory(factory);       
            computeShadowPosition();
            this.setOpaque(true);
        public ShadowRenderer getShadowFactory() {
            return factory;
        public void setShadowFactory(ShadowRenderer factory) {
            if (factory == null) {
                factory = new ShadowRenderer();
            if (factory != this.factory){
                if (this.factory != null) {
                    this.factory.removePropertyChangeListener(this);
                this.factory = factory;
                this.factory.addPropertyChangeListener(this);
                shadow = null;
                repaint();
        public float getAngle() {
            return angle;
        public void setAngle(final float angle) {
            this.angle = angle;
            computeShadowPosition();
            repaint();
        public int getDistance() {
            return distance;
        public void setDistance(final int distance) {
            this.distance = distance;
            computeShadowPosition();
            repaint();
        private void computeShadowPosition() {
            double angleRadians = Math.toRadians(angle);
            distance_x = (int) (Math.cos(angleRadians) * distance) - factory.getSize() ;
            distance_y = (int) (Math.sin(angleRadians) * distance) - factory.getSize();
        @Override
        public boolean isOpaque() {
            return false;
        @Override
        public void doLayout() {
            super.doLayout();
            shadow = null;
        @Override
        public void paint(Graphics g) {
             Graphics g3 = g.create();
                BufferedImage buffer =
                        GraphicsUtilities.createCompatibleTranslucentImage(getWidth(),
                                                                           getHeight());
                Graphics2D g2 = buffer.createGraphics();
                super.paint(g2);
                shadow = factory.createShadow(buffer);          
                g2.dispose();
                g.setClip(g3.getClip().getBounds().x,
                          g3.getClip().getBounds().y,
                          g3.getClip().getBounds().width + 20,
                          g3.getClip().getBounds().height + 20);
                g.drawImage(shadow, distance_x, distance_y, shadow.getWidth(), shadow.getHeight(), null);        
                g.drawImage(buffer, 0, 0, null);         
                System.out.println("distance_x = " + distance_x + "; distance_y = " + distance_y);           
         g.setClip(g3. getClip());
        public void propertyChange(PropertyChangeEvent evt) {
            shadow = null;
            computeShadowPosition();
            repaint();
    }

    Modifying the clip to draw outside of the frame bounds is not a good idea. Swing expects components to paint only within their bounds. So when you move the frame from position A to position B, swing takes care that the old frame bounds are repainted by the underlying component (desktop pane). The stuff you painted outside of the frame bounds will not be cleared. Maybe you will have some success if you ask the desktop pane to repaint after every resize/move of the internal frame.
    The approach with the empty border seemed more promising and I gave it a try. First thing I found is that some InternalFrameUI's install their own border on the frame. See the updateUI() method below to see how I tried to work around that problem. This works for Metal, Motif and Windows L&F (only when using the windows classic theme).
    Second thing I found is that when using the windows XP theme, the BasicInternalFrameUI.Handler.layoutContainer() method sets the bounds of the internal frame's "north pane" to the whole width of the frame (ignoring any borders). If you really only need this to work in one specific L&F, I imagine it would be possible to subclass the WindowsInternalFrameUI, override the createNorthPane() method to return a subclass of WindowsInternalFrameTitlePane which in turn override the setBounds() method, reducing the width by the amount needed for the shadow.
    The code contains the empty border approach (not working for windows L&F with XP theme enabled). I was not able to test any linux or mac L&Fs.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.UIManager;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import org.jdesktop.swingx.graphics.GraphicsUtilities;
    import org.jdesktop.swingx.graphics.ShadowRenderer;
    public class DropShadowInternalFrame extends JInternalFrame {
        private static final int SHADOW_WIDTH = 4;
        private ShadowRenderer shadowRenderer = new ShadowRenderer(SHADOW_WIDTH, 0.5f, Color.BLACK);
        private BufferedImage shadow = null;
        public DropShadowInternalFrame() {
            super("Internal Frame", true, true, true, true);
            // BasicInternalFrameUI.Handler.layoutContainer() uses this property:
            // UIManager.put("InternalFrame.layoutTitlePaneAtOrigin", false);
        public static void main(String[] args) throws Exception {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            DropShadowInternalFrame dropShadowInternalFrame = new DropShadowInternalFrame();
            dropShadowInternalFrame.setOpaque(false);
            dropShadowInternalFrame.setBounds(20, 20, 300, 300);
            dropShadowInternalFrame.setVisible(true);
            JDesktopPane desktopPane = new JDesktopPane();
            desktopPane.add(dropShadowInternalFrame);
            desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
            JFrame frame = new JFrame("DropShadowInternalFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(desktopPane);
            frame.setSize(500, 500);
            frame.setVisible(true);
        @Override
        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            int w = getWidth();
            int h = getHeight();
            if (shadow == null || shadow.getWidth() != w || shadow.getHeight() != h) {
                // recreate shadow if frame size changed
                BufferedImage frameImg = GraphicsUtilities.createCompatibleTranslucentImage(
                        w - 2 * SHADOW_WIDTH, h - 2 * SHADOW_WIDTH);
                super.paint(frameImg.createGraphics());
                shadow = shadowRenderer.createShadow(frameImg);
            g2.drawImage(shadow, 0, 0, null);
            // Motif ALMOST honors the empty internal frame border
            // comment this line out to see interesting artifacts in Motif LaF
            g2.setClip(0, 0, w - 2 * SHADOW_WIDTH, h - 2 * SHADOW_WIDTH);
            super.paint(g2);
            g2.dispose();
        public void updateUI() {
            super.updateUI();
            // wrap the border of the UI delegate inside our empty border
            setBorder(new CompoundBorder(new EmptyBorder(0, 0, 2 * SHADOW_WIDTH, 2 * SHADOW_WIDTH), getBorder()));
    }

  • Container panels transparent in JInternalFrame with Windows XP Style

    Hi All
    I have a problem with a GUI where panels extending java.awt.Container (added to JInternalFrame) are transparent when using Windows XP Style (Windows XP Pro). The components added to the Container (for example JButton, JComboBox etc.) paint correctly but the surrounding space of the Container to which they belong is translucent such that the desktop below can be seen.
    When I switch to Windows Classic Style this does not happen. I'm using JDK6.0.
    Has anyone encountered this problem?
    Help appreciated
    Lance

    Just an update; this is the config I'm using to bootstrap the app (in main):
      UIManager.put("swing.boldMetal", Boolean.FALSE);
      UIManager.put("ToolTip.background", Color.YELLOW);
      JDialog.setDefaultLookAndFeelDecorated(true);
      JFrame.setDefaultLookAndFeelDecorated(true);
      Toolkit.getDefaultToolkit().setDynamicLayout(true);
      System.setProperty("sun.awt.noerasebackground","true");
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());The GUI is assembled from basic panels which extend Container, typical example below:
    public class BottomContainer extends Container implements ActionListener {
         private ActionListener handler;
         private ModeButton closeCancelButton;
         private JProgressBar progressBar;
         private ResourceBundle bundle;
         public BasicBottomContainer(ResourceBundle bundle) {
              super();
              this.bundle = bundle;
              createGui();
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              ActionEvent xEvent = null; // translated event
              if (source == closeCancelButton) {
                   ButtonModes mode = ((ModeButton) source).getMode();
                   if (mode == ButtonModes.CANCEL) {
                        xEvent = new ProxyActionEvent(ActionProxies.CANCEL_BUTTON);
                   } else if (mode == ButtonModes.CLOSE) {
                        xEvent = new ProxyActionEvent(ActionProxies.CLOSE_BUTTON);
                   } else {
                        throw new IllegalArgumentException("Mode not defined");
              } else {
                   throw new IllegalArgumentException("Source not defined");
              handler.actionPerformed(xEvent);
         private void createGui() {
              setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
              progressBar = new JProgressBar();
              progressBar.setMinimum(0);
              progressBar.setMaximum(100);
              progressBar.setVisible(false);
              JPanel progressPanel = new JPanel();
              progressPanel.setLayout(new BorderLayout());
              progressPanel.add(progressBar, BorderLayout.CENTER);
              GuiUtils.setFixedSize(progressPanel, 200, 13);
              progressPanel.setVisible(false);
              ButtonModes mode = ButtonModes.CLOSE;
              closeCancelButton = new ModeButton(bundle.getString("closeButton"), mode);
              localeChangeList.add(closeCancelButton, "closeButton");
              closeCancelButton.setMinimumSize(new Dimension(80, 25));
              closeCancelButton.addActionListener(this);
              add(GuiUtils.rigidArea(15, 55)); // spacing with left-hand border & height
              add(progressPanel);
              add(Box.createHorizontalGlue()); // push apart
              add(closeCancelButton);
              add(GuiUtils.rigidArea(15, 0)); // spacing with right-hand border
              setVisible(false);
         public void updateRefreshProgress(int refreshProgress) {
              progressBar.setValue(refreshProgress);
         public void setCloseCancelButtonMode(ButtonModes mode) {
              closeCancelButton.setMode(mode);
         public void setHandler(ActionListener handler) {
              this.handler = handler;
    }The Container above is then attached in the main GUI something like this:
    public abstract class TestView extends AbstractView {
         protected TopContainer topContainer;
         protected MiddleContainer middleContainer;
         protected BottomContainer bottomContainer;
         public AbstractView() {
              createGui();
         private void createGui() {
              topContainer = new TopContainer(model.getBundle());
              middleContainer = new MiddleContainer();
              bottomContainer = new BottomContainer(model.getBundle());
              infoPanel.setVisible(false);
              container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
              container.add((Container) topContainer);
              container.add((Container) middleContainer);
              container.add(infoPanel.getContainer());
              container.add((Container) bottomContainer);
         protected void dispose() {
              super.dispose();
         public final void showGui(boolean visible) {
              super.showGui(visible);
              topContainer.setVisible(true);
              middleContainer.setVisible(true);
              bottomContainer.setVisible(true);
    }It appears that all the components (e.g. BottomContainer, TopContainer etc)
    which extend Container are transparent but I'm not able to replicate it with a simpler class (the panels are always opaque in simpler setup).
    Has anyone seen this before (as I mentioned above, this only happens when I set my config for Windows XP Pro to 'Windows XP Style' in the Control Panel).
    Help much appreciated
    Lance

  • JInternalFrame listener...help!

    Ok, i am making a paint program where the pictures are stored in JInternalFrames.
    when the user closes a frame i have a InternalFrame listener as follows:
    public void internalFrameClosing(InternalFrameEvent e) {
              JInternalFrame fr = desktop.getSelectedFrame();
              if(fr.getLayer() == JDesktopPane.DEFAULT_LAYER)
    int response = JOptionPane.showConfirmDialog(null, "This will delete any unsaved changes, would you like to save?",
                   "Confirm Save",
                   JOptionPane.YES_NO_CANCEL_OPTION,
                   JOptionPane.WARNING_MESSAGE );
             if (response == JOptionPane.CANCEL_OPTION)
                  //System.out.println("woof");
                  return;
                if (response == JOptionPane.YES_OPTION)
                    doSave();
            close();
          }for some reason when i press cancel it doesnt cancel the closing of the frame, i thought return would work but clearly not.
    Is there any other way to stop the frame closing once the X has been clicked?
    thanks

    when creating the frames, call setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    that way it won't close without you disposing it.
    Also, unless you need the layer check for something else, you don't need that.

  • The problem of the Canvas and JInternalFrame

    I have some problem with the Canvas and JInternalFrame, my application contains serval internalframes and each has one canvas, but i found that canvas is at the top z-order of the window. so it result in that the canvas is at the same z-level, which confuse very much.
    who can help me with this problem, thanks.

    I think the problem stems from mixing AWT and Swing components (non-lightweight and lightweight)
    if the reason you are using a canvas is for the paint method; do away with them and just use a JPanel (which you can use the paint method within)
    hope this helps?!
    Simon

  • Repaint JInternalFrame transparent over a picture

    Hi,
    I have a problem using a non-opaque JInternalFrame, with a content pane which has a background with ALPHA.
    When I move the frame over a picture, it does not repaint() automatically.
    But, when I use a ComponentListener to repaint() it manually (in componentMoved() method), there are flikerings...
    I noticed that, when resizing the frame, the "automatic" repaint is good (really good).
    Does anybody know how to "use" the same way to repaint() the frame when I move it ?
    Here is an example :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EssaiRepaint {
    public static void main(String[] aArgs) {
    JFrame oFrame = new JFrame("Repaint Test"); oFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Container oContent = oFrame.getContentPane();
    oContent.setLayout(new BoxLayout(oContent, BoxLayout.Y_AXIS));
    JDesktopPane oDesktop = new JDesktopPane();
    oContent.add(oDesktop);
    ImageIcon oIcon = new ImageIcon("aRatherBigPic.jpg");
    JLabel oLabel = new JLabel(oIcon);
    oLabel.setSize(350,250);
    oDesktop.add(oLabel, JLayeredPane.DEFAULT_LAYER, 0);
    final JInternalFrame oIFrame = new JInternalFrame("Test", true, true , true, true);
    // Try both by uncommenting the following lines
    /*oIFrame.addComponentListener(new ComponentAdapter() {
    public void componentMoved(ComponentEvent aEvent) {
    oIFrame.repaint();
    oIFrame.setOpaque(false);
    Color oBg = oIFrame.getContentPane().getBackground();
    oIFrame.getContentPane().setBackground(new Color(oBg.getRed(), oBg.getGreen(), oBg.getBlue(), 128));
    oIFrame.setSize(200,200);
    oIFrame.setVisible(true);
    oDesktop.add(oIFrame, JLayeredPane.DEFAULT_LAYER, 0);
    oFrame.setSize(500,600);
    oFrame.setVisible(true);
    Thanks a lot,
    Luc.

    Not sure if this is what you are looking for, but I think the flickering is caused because multiple componentMoved events are generated and Swing can't repaint fast enough. I don't know how to speed up the painting so I deferred the repaint until the component is finished moving:
    final Timer timer = new Timer(50, new ActionListener()
         public void actionPerformed(ActionEvent e)
              oIFrame.repaint();
    timer.setRepeats( false );
    oIFrame.addComponentListener(new ComponentAdapter()
         public void componentMoved(ComponentEvent aEvent)
              if (timer.isRunning())
                   timer.restart();
              else
                   timer.start();
    });

Maybe you are looking for

  • Change System Icons (How to...)

    I use Leo's Icon Archive a lot and I found a nice set to update my OSX with, but I don't know how. the Blend icon set is this one and all icons come as ICNS file extension, if I copy and replace the icon of my Hard drive using copy paste in the Get I

  • Is there an alternative flash player I can use for Firefox mobile

    I can't access my Facebook games it says the phone doesn't support abode is there an alternative I can use

  • Please begin to work more for the future dear Canon.

    I love Canon and I am a Canon guy for long time, but dear Canon, you lose so much time brush up models that in short time would be overwhelmed (EOS models), please take a look at the New Pentax 645D Medium Format, Hasselblad and Phase One which is th

  • Runtime error in MSS - Team- General Information- Related links- Employee Dates

    Hello All, We recently upgrade from 7.01 to 7.31, we also updated the respective XSS components also to compatible levels. All applicatoins are coming up well except the Employee dates and Desciplinary actions based on related links under MSS ->Team-

  • Macbook running slow after mountain lion update

    why? i have 2 gb of RAM, that should be more than enough, right? firefox is running slow, everything is freezing. i have barely used any of my hard drive space with it being at 225.61 gb free out of 249.2 gb. its really frustrating.....