An Image JPanel, A semi-transparent JPanel, and non-opaque components

This is a more intelligent re-asking of the question I posed here: http://forum.java.sun.com/thread.jspa?threadID=579298&tstart=50.
I have a class called ImagePane, which is basically a JPanel with an image background. The code is much like the ImagePanel posted by camickr, discussed in this topic: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=316074 (except mine only draws the image, it does not tile or scale it).
On top of my ImagePane, I can place another component, TransparentContainer. This again extends JPanel, only a color is specified in the constructor, and it is drawn at about 70% opacity. This component is meant to help increase the readability of text components that blend with the background image, without blocking out the background image completely.
This works very well, until I need to add a component, like, say, a non-opaque JRadioButton in a ButtonGroup. When you select a new JRadioButton at runtime, the semi-transparent JPanel fills with a combination of a completely opaque color (the one specifies to the TransparentContainer) and garbage from the non-opaque component being redrawn.
I have noticed that the UI is restored to being non-messed up if you place another application window on top of it and then move it. So apparently, one solution is to redraw the entire UI, or just the part that has the JRadioButton on it, every time the radio button is clicked. However, this seems unnecessarily complicated. It seems to me that I am missing something in my TransparentContainer's paintComponent() method. Does anyone have any ideas?
Here is my TransparentContainer code, if it will help:
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public final class TransparentContainer extends JPanel
     /* Private Fields: For use only by this class.
      *  These fields hold information needed by more
      *  than one method of this class.
     private boolean fullTransparencyEnabled;
     private Color baseColor;
     private Color outerBorderColor;
     private Color innerBorderColor;
     private int obw;
     private int ibw;
     private int cbw;
     /* -- START OF METHODS -- */
     /* public TransparentContainer(Color color, boolean fullTrans)
      *   Initiallizes the transparent container object
      *   with 'color' as its base color.
     public TransparentContainer(Color color, boolean fullTrans)
          fullTransparencyEnabled = fullTrans;
          baseColor = color;
          Color borders[] = findBorderColors();
          outerBorderColor = borders[0];
          innerBorderColor = borders[1];
          obw = 3;
          ibw = 1;
          cbw = obw + ibw;
     /* private Color[] findBorderColors(Color base)
      *   Calculates the colors for the outer and inner
      *   borders of the object based on the base color.
     private Color[] findBorderColors()
          Color borders[] = new Color[2];
          int colorData[] = new int[9];
          colorData[0] = getBaseColor().getRed();
          colorData[1] = getBaseColor().getGreen();
          colorData[2] = getBaseColor().getBlue();
          colorData[3] = colorData[0] - 50;          // outerBorder red
          colorData[4] = colorData[1] - 45;          // outerBorder green
          colorData[5] = colorData[2] - 35;          // outerBorder blue
          colorData[6] = colorData[0] + 30;          // innerBorder red
          colorData[7] = colorData[1] + 30;          // innerBorder green
          colorData[8] = colorData[2] + 20;          // innerBorder blue
          /* Make sure the new color data is not out of bounds: */
          for (int i = 3; i < colorData.length; i++)
               if (colorData[i] > 255)
                    colorData[i] = 255;
               else if (colorData[i] < 0)
                    colorData[i] = 0;
          borders[0] = new Color(colorData[3], colorData[4], colorData[5]);
          borders[1] = new Color(colorData[6], colorData[7], colorData[8]);
          return borders;
     /* public Color getBaseColor()
      *   Returns the baseColor of this object.
     public Color getBaseColor()
          return baseColor;
     /* public Color getOuterColor()
      *   Returns the outerBorderColor of this object.
     public Color getOuterColor()
          return outerBorderColor;
     /* public Color getInnerColor()
      *   Returns the innerBorderColor of this object.
     public Color getInnerColor()
          return innerBorderColor;
     /* public boolean getFullTransEnabled()
      *   Returns whether or not this object will render
      *   with all of its transparency effects.
     public boolean getFullTransEnabled()
          return fullTransparencyEnabled;
     /* protected void paintComponent(Graphics g)
      *   Paints the component with the borders and colors
      *   that were set up in above methods.
     protected void paintComponent(Graphics g)
          Graphics2D g2d = (Graphics2D) g;
          AlphaComposite alphaComp;
          g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
          g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                        RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
          g2d.setColor(getBaseColor());
          /* Draw the main body of the component */
          if (getFullTransEnabled())
               alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
               g2d.setComposite(alphaComp);
          else
               alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
               g2d.setComposite(alphaComp);
          g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
          alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
          g2d.setComposite(alphaComp);
          /* Draw the inner border: */
          g2d.setColor(getInnerColor());
          g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
          g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
          g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
          g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
          /* Draw the outer border: */
          g2d.setColor(getOuterColor());
          g2d.fillRect(0, 0, obw, super.getHeight()); // left border
          g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
          g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
          g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
          alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
          g2d.setComposite(alphaComp);
          g2d.dispose();
}

I added the main method to your TransparentContainer class ...
     public static void main(String[] args) {
          JFrame f = new JFrame("test transparent container");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          TransparentContainer tc = new TransparentContainer(Color.RED, true);
          JLabel label = new JLabel("Hello, World!");
          tc.add(label);
          f.getContentPane().add(tc);
          f.setSize(800, 600);
          f.setVisible(true);
     }...using the code you posted the label was not shown. I modified your paintComponent(Graphics g) method and I did this (see the areas in bold):
     /* protected void paintComponent(Graphics g)
      *   Paints the component with the borders and colors
      *   that were set up in above methods.
     protected void paintComponent(Graphics g)
          // Call super so components added to this panel are visible
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g;
          AlphaComposite alphaComp;
          g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
          g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                        RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
          g2d.setColor(getBaseColor());
          /* Draw the main body of the component */
          if (getFullTransEnabled())
               alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
               g2d.setComposite(alphaComp);
          else
               alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
               g2d.setComposite(alphaComp);
          g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
          alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
          g2d.setComposite(alphaComp);
          /* Draw the inner border: */
          g2d.setColor(getInnerColor());
          g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
          g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
          g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
          g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
          /* Draw the outer border: */
          g2d.setColor(getOuterColor());
          g2d.fillRect(0, 0, obw, super.getHeight()); // left border
          g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
          g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
          g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
          alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
          g2d.setComposite(alphaComp);
          // Do not dispose the graphics
          // g2d.dispose();          
     }...seems to work fine now. Perhaps you should also add methods or additional constructors so the user can easily change the transparency level...and add some javadoc comments to your constructors ...at a first glance I did not know what fullTrans was
public TransparentContainer(Color color, boolean fullTrans)good luck!!

Similar Messages

  • Chargeable Components and Non-Chargeable Components in Routing

    Dear Experts
    I am investigating about relationship of Routing and Chargeable Components, Non-Chargeable Components.
    Is it possible that one routing has Chargeable Components and Non-Chargeable Components in its task?
    Below is instance.
    This routing is to manufacture laptop.
    10: assemble1       Chargeable Components
    20: assemble2       self-manufacture
    30: quiality check   self-manufacture
    40: coating             Non-Chargeable Components
    50: packaging        self-manufacture
    If this is possible, please give the information about config and master setting.
    Or should I divide the task like below?
    To make  halfway laptop
    10: assemble1      Chargeable Components
    To make laptop without packaging
    10: assemble2      self-manufacture
    20: quiality check  self-manufacture
    To make laptop with coating
    10: coating            Non-Chargeable Components
    To make completely laptop
    10: packaging       self-manufacture
    Kind regards,

    Hi,
    You can use this Routing 
    Below is instance.
    This routing is to manufacture laptop.
    10: assemble1 Chargeable Components
    20: assemble2 self-manufacture
    30: quiality check self-manufacture
    40: coating Non-Chargeable Components
    50: packaging self-manufacture
    But in THIS Routing , if you check you have the Assembly indicator tick against the operation 10 and 20
    If you click over there ,it will go the  the assembly Routing for this 10 and 20 operation, since you mentioned as assembly. so the component that you assigned for this operaions are assembly components.

  • Zoom JPanel and all its components

    Folkses,
    I have a JPanel which contains a lot of different components, containers with components, etc.
    The components are either images or drawn 'by hand' (overwritten paintComponent).
    Is there a simple way of zooming in/out to get the whole picture larger/smaller? I know Graphics2D.scale() but I'm hestitant to implement this in each and every component of my JPanel.
    Thanx,
    Thomas
    PS: searching the forum I only found answers on zooing images...

    Hello camickr,
    I am also very much interested in this.
    Well, you can create an image of a panel and then zoom the image.But I think this will not increase the components' bounds and components would not respond mouse events etc. correctly. Am I right? Then, what is the way of zooming such that all the components respond to events correctly.
    I hope you have done something like this before and help us.
    Thanks!

  • How to eliminate background of an image while Maintaining semi-transparent mid-ground.

    Sorry if the topic name is slightly inaccurate or if my question seems amaturish, I'm fairly new to using PS. For a project I would like to delete the black background of this image http://calibermag.org/wp-content/uploads/2013/11/2534069-Action-Bronson-617.jpg and replace it with another background, however I would like to keep the smoke that's lingering over the background. Are there any techniques or tools I could use to delete the background and the black behind the smoke without directly effecting the smoke?

    That image will respond well to the [Refine Edge] feature.
    Basically, select the dude with e.g., the Quick Select Tool, then use Refine Edge and paint the Refine Radius Tool over the smoke.
    This tutorial gives the technique in some detail.  The technique shown works in the most current version of Photoshop.
    http://tv.adobe.com/watch/the-russell-brown-show/masking-basics-in-photoshop-cs5/
    Smoke isn't too terribly different, conceptually, than hair.
    -Noel

  • Is there a way to create a semi-transparency with Java?

    I would like to be able to create a semi transparent form and I was does anyone know how to do this?

    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CompositeTest extends JPanel {
        private BufferedImage backImage, frontImage;
        private float alpha = 1;
        public CompositeTest() throws IOException {
            backImage = ImageIO.read(new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"));
            frontImage = ImageIO.read(new URL("http://today.java.net/jag/Image54-small.jpeg"));
        public Dimension getPreferredSize() {
            return new Dimension(backImage.getWidth(), backImage.getHeight());
        public void setAlpha(float alpha) {
            this.alpha = alpha;
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            int x = (getWidth() - backImage.getWidth())/2;
            int y = (getHeight()- backImage.getHeight())/2;
            g2.drawRenderedImage(backImage, AffineTransform.getTranslateInstance(x, y));
            Composite old = g2.getComposite();
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            x = (getWidth() - frontImage.getWidth())/2;
            y = (getHeight()- frontImage.getHeight())/2;
            g2.drawRenderedImage(frontImage, AffineTransform.getTranslateInstance(x, y));
            g2.setComposite(old);
        public static void main(String[] args) throws IOException {
            final CompositeTest app = new CompositeTest();
            JSlider slider = new JSlider();
            slider.addChangeListener(new ChangeListener(){
                public void stateChanged(ChangeEvent e) {
                    JSlider source = (JSlider) e.getSource();
                    app.setAlpha(source.getValue()/100f);
            slider.setValue(100);
            JFrame f = new JFrame("CompositeTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            cp.add(app);
            cp.add(slider, BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • A simple dialog with semi-transparent border (MFC)

    Hi,
    I have to make a image dialog with semi-transparency border in MFC.
    I had web surfing all the day and found this solution in the codeproject.
    http://www.codeproject.com/Articles/42032/Perfect-Semi-transparent-Shaped-Dialogs-with-Stand
    But it creates two dialogs to make a semi-transparent dialog and the mechanism was so complex.
    And the release of the dialog object is difficult so that it may have memory leaks.
    I want a dialog (background is an image) with a semi-transparent border (corner - rounded).
    And I have to make it with only one dialog. If it's possible, how can I do it?
    Please help me, Thank you.

    The child control will become semi-transparency as your dialog.
    Do you want to show some child control on your dialog? If yes, you need the second dialog to host your child control. 
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How can I capture a semi transparent window?

    Hello all
    I am trying to grab an image of a semi transparent window into a bitmap. I have tried using both CopyFromScreen and BitBlt using the window handle but in both cases all I get is the image from behind the window I want to catch, it's like the semi transparent
    window is completely invisible to both capture methods. Is there any way I can capture the window I want?
    Thanks
    Rich

    Here is an example. You can try it in a new form project with 1 Button and 1 PictureBox added to the form. As i said, it is just an example so, when it is run the form will be partialy transparent. Click the button and it will capture the whole screen including
    your transparent form. Then it will set the forms opacity back to 1.0 so you can see that the transparent form was captured in the image.
     You will need to set it up to be used in a practical way. This is just a quick test example.
    Imports System.Runtime.InteropServices
    Public Class Form1
    Private Const CAPTUREBLT As Integer = &H40000000
    Private Const SRCCOPY As Integer = &HCC0020
    <DllImport("gdi32.dll", EntryPoint:="BitBlt")> _
    Private Shared Function BitBlt(ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function
    <DllImport("user32.dll", EntryPoint:="GetDC")> Private Shared Function GetDC(ByVal hWnd As System.IntPtr) As System.IntPtr
    End Function
    <DllImport("user32.dll", EntryPoint:="ReleaseDC")> Private Shared Function ReleaseDC(ByVal hWnd As System.IntPtr, ByVal hDC As System.IntPtr) As Integer
    End Function
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'set this form so it is partialy transparen. Just to show it was captured for this example
    Me.Opacity = 0.5
    PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'if the picturebox has an Image the Dispose it first
    If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
    'define the rectangle area of the screen to capture (whole screen in this case)
    Dim CaptureRectangle As Rectangle = Screen.PrimaryScreen.Bounds
    'Assign the new image captured from the screen to the picturebox image
    PictureBox1.Image = CaptureScreenImage(CaptureRectangle)
    'just so you can see the image better set the form`s opacity back to 1.0
    Me.Opacity = 1.0
    End Sub
    Private Function CaptureScreenImage(ByVal rect As Rectangle) As Bitmap
    Dim scrnHdc As IntPtr = GetDC(IntPtr.Zero)
    Dim bmp As New Bitmap(rect.Width, rect.Height)
    Using grx As Graphics = Graphics.FromImage(bmp)
    Dim grxHdc As IntPtr = grx.GetHdc()
    BitBlt(grxHdc, 0, 0, rect.Width, rect.Height, scrnHdc, rect.X, rect.Y, SRCCOPY Or CAPTUREBLT)
    grx.ReleaseHdc(grxHdc)
    ReleaseDC(IntPtr.Zero, scrnHdc)
    End Using
    Return bmp
    End Function
    End Class
    If you say it can`t be done then i`ll try it

  • Semi-transparent Screen Issue X1 2014

    Hey
    I have this strange issue with my X1 (had it for a few months now but had the issue since the beginning).
    Some colors, such as grey, make the edges of my screen semi-transparent as in I can see through to the application behind it.
    I don't believe this is a screen issue but wondering if anyone else has experience this problem.
    I have attached an image that makes it happen (try viewing it full screen and let me know what you see).
    I have also attached an image of what I see.
    http://1drv.ms/1qbIYx1
    Does anyone else have this problem?

    Your descriptions "semi-transparent screen" and "app behind the screen" are very confusing and it's difficult to understand what you mean.
    What exactly is the running state of the computer? What apps are running in your photos (with the "XO" in the first picture and the vertical bar in the second picture)? Describe steps to produce the result.
    I think you're saying that you are running one app and launch another app on top of it, and you can see the first app bleeding through. The first app isn't really bleeding through -- it was burned into screen (also known as image retention or ghosting). It's a screen display hardware problem that is common on some models of Lenovo laptops.

  • Using a fake semi-transparency - what's really possible?

    Hi,
      I'm just now moving into DW CS4 (from cs3) and I'm on an intel iMac. I'm trying to make a table background that is semi-transparent while KEEPING text and photos 100% opaque. I'm already familiar with this kind of code: (just improvising here):
    .tableMain {
    background: transparent;
    filter=alpha(opacity=50);
    opacity=.5
    But this makes EVERYTHING semi-transparent - content and all. I'd love to know if it is possible to keep the content fully in view.
    I've tried making a semi-transparent GIF or PNG background in Photoshop CS4 and using it for the table background, but that doesn't seem to work.
    I did discover this (perhaps unique to my site) solution for a fake semi-transparency: Since I've got a gradient background on my site (see www.frankbright.com/History.htm ), I took a 'Screen Snapshot' of the background, from the bottom of the navigation to as far down as I could go. Then I used PS CS4 to expand the canvas and color down to cover my long pages. (See Jazz Links)
    Then I used PS levels to darken the snapshot very slightly, so as to intimate a gray semi-transparent effect. Then I simply used that snapshot as the table background.
    This looks better on the long, clearer pages that have only text content. With the index3 home page, however,  you don't sense the semi-transparent effect I'm going for as much.
    I've also noticed the 'Extensions' area of the CSS interface in DW - does this have anything to do with what I'm trying to do?
    Anyways, I'm open to ideas, if anyone could suggest any.
    Many Thanks, Frank B.

    Hi
    You did not say what the problem was.
    others viewing this thread. please read -
    As for the colors of the background gradient using IEFilters, (for those who did not know on the forum, the IEFilter for background gradient was available since IE4.5, circa 1996, and all filters since IE5, circa 1998) you will need to adjust these as required. Luckily enough most background gradients go from one color to white or a lighter color of the starting color.
    For FF and Safari see - http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/, http://webkit.org/blog/175/introducing-css-gradients/.
    Google Chrome uses the webkit declaration, but unfortunately Opera does not support the feature, (use a standard background color at the beginning of the declaration) and FF only from version 3.6. But with the upgrading for FF users normally being 70+% within 6 months, this does mean that 85% of users will support the background gradient.
    PZ
    Edit: If you are using a css reset then it may be worth placing the position: relative; statement in this, as these normally include all the elements from H1 to pre.
    Message was edited by: pziecina

  • Question about semi-transparent jpgs

    Hello again.
    I am trying to display a semi-transparent jpg in the Graphics Layer, having a code that seems to be right but the image is not transparent after all..
    I am wondering whether my source *jpg.File is the problem..
    Is it possible that all input Graphics that are supposed to be transparent need an
    alpha, in order to make the effect happen? I am really stuck..
    Thank you for helping me out,
    Alex.

    If you want images to be semi-transparent then you either need to use images that have an alpha channel (e.g. PNGs) or that use a transparent colour.. The only alternative is to use a matte that handles the transparency for you, but this is a more complex solution.
    Steve.

  • Having a JPanel 'float' semi-transparently over another component

    I am a programmer of a java project for our company.
    Managemnt decided that when a certain event happens, we need to 'semi-disable' a certain text area (in a JScrollPane), and have a floating message with a progress bar on top of this text area, but be semi-transparent, so you can still read the text under it.
    (Basically, they want it to look like a html page with a floating, semi-transparent DIV, because that is how another group mocked it up).
    I am trying to implement this, but am running into problems.
    Here is what I have, below I'll tell you what is wrong with it.
         * The purpose of this class is to have a scroll pane that can have it's contents partially covered by another panel
         * while still being able to read both the original panel and the new covering content, and still being able to scroll
         *the content under the covering panel.
        public class JOverlayScrollPane extends JScrollPane{
            private JPanel overlay = null;
            private Insets overlayInsets = null;
            private java.awt.AlphaComposite blend = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f);
            private ComponentAdapter cl = null;
            public void setOverlay(JPanel pan, Insets inset){
                overlay = pan;
                overlayInsets = inset;
                if(cl != null){
                    cl = new ComponentAdapter(){
                        public void componentResized(ComponentEvent e){
                            resizeOverlay();
                resizeOverlay();
                repaint();
            public void paint(Graphics g){
                super.paint(g);
                if(g instanceof Graphics2D && overlay !=null){
                    Graphics2D g2 = (Graphics2D)g;
    //                g2.setComposite(blend);
                    //overlay.paint(g2);
                    paintStuff(g,overlay);
            private void resizeOverlay(){
                if(overlay != null){
                    Dimension size = getSize();
                    int x = 0;
                    int y = 0;
                    if(overlayInsets !=null){
                        x = overlayInsets.left;
                        y = overlayInsets.top;
                        size.width = size.width - overlayInsets.left - overlayInsets.right;
                        size.height = size.height - overlayInsets.top - overlayInsets.bottom;
                    overlay.reshape(x,y, size.width, size.height);
                    overlay.doLayout();
                    overlay.validate();
            private void paintStuff(Graphics g,Component c){
                if(c != null){
                    c.paint(g);
                    if(c instanceof Container){
                        Container cont = (Container)c;
                        for(int i=0;i<cont.getComponentCount();i++){
                            Component cc = cont.getComponent(i);
                            paintStuff(g,cc);
        }//end of overlay scroll pane(I am having problems, so for now, the alpha blend is commented out).
    The first version didn't have the paintStuff() method (it just called paint). This just drew a big grey box, now of the sub-components of the passed in JPanel were drawing. I added the do layout and validate calls, without success.
    Then I added the paintStuff call, and all the subcomponents now, draw, but they all draw at 0,0.
    Questions
    1. Is the the correct approach to do this, or sould I be playing with the glass pane or some other approach?
    2. It seems that the overlay panel isn't being layed out / doens't paint it's children correctly. Is this because it isn't really part of the layout (i.e. it has no parent / is never added to a container) or am I just missing a step in 'faking' adding it to a layout?
    3. I'm sure I could just override paint and paint my own stuff (hand draw the text and a progress bar), but I would really like to put everything on one JPanel as what we want to display my be different in the future. I know that I manually ahve to call repaint on this scrollpane if one of the components on the overlay JPanel change in appearence (the progress bar especailly), and that they won't get events (I don't care about this as they are all non-interactive for now). Is this a viable approach, or is there a better way to do this?
    Thanks

    Wow, good answer.
    I never concidered using a root pane other than as it is used in JFrame.
    Very cool answer.
    Here is my origional code modifed with JN_'s idea, which cleaned up a repaint issue I was having.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TransparentPanel extends JFrame implements ActionListener
        ProgressPanel progressPanel;
        int progressCount;
        public TransparentPanel()
            super( "TransparentPanel Test");
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            JPanel panel = new JPanel( new BorderLayout() );
            JTextArea area = new JTextArea( 20, 40 );
            JRootPane pane = new JRootPane();
            pane.setContentPane( new JScrollPane( area ) );
            panel.add( pane, BorderLayout.CENTER );
            //panel.add( new JScrollPane( area ), BorderLayout.CENTER );
            progressPanel = new ProgressPanel();
            pane.setGlassPane( progressPanel );
            JPanel buttonPanel = new JPanel( new FlowLayout());
            JButton button = new JButton( "Show" );
            button.setActionCommand("SHOW");
            button.addActionListener( this );
            buttonPanel.add( button );
            button = new JButton( "Hide" );
            button.setActionCommand("HIDE");
            button.addActionListener( this );
            buttonPanel.add( button );
            panel.add( buttonPanel, BorderLayout.SOUTH);
            setContentPane( panel );
            pack();
            setLocationRelativeTo( null );
            setVisible( true );
        public static void main( String[] args )
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
                e.printStackTrace();
            new TransparentPanel();
        public class ProgressPanel extends JPanel
            Color bg = new Color( 225, 221, 221, 100 );
            Color fg = new Color( 170, 234, 202, 100 );
            int progress;
                   setOpaque( false );
            public void setProgress( int n )
                 setVisible( n > 0 && n <= 100 );
                progress = n;
                repaint();
            public void paint( Graphics g )
                if( isVisible() )
                    Rectangle bounds = getBounds();
                    g.setColor( bg );
                    g.fillRect( bounds.x, bounds.y, bounds.width, bounds.height );
                    g.setColor(  fg );
                    int width = (int)(((double)progress/100)*bounds.width);
                    int height = (int) (((double)bounds.height)*.1);
                    int y = (int) (((double)bounds.height)*.4);
                    g.fillRect( bounds.x,y,width,height);
         * Invoked when an action occurs.
        public void actionPerformed(ActionEvent e)
            String cmd = e.getActionCommand();
            if(cmd.equals( "SHOW" ) )
                progressCount+= 10;
                if( progressCount > 100 )
                    progressCount = -1;
            else if( cmd.equals("HIDE" ) )
                progressCount = -1;
            progressPanel.setProgress( progressCount );
    }

  • Drawning text/images in a JPanel and then resizing/moving it with the mouse

    Hello ebverybody!
    I need to be able to draw some text objects in a JPanel and then resize/move it with the mouse... How could I do that!? Same for some images loaded from jpg files...
    Should I just paint the text and then repaint when the mouse selects it? How to do this selection?! Or should use something like a jLabel and then change it`s font metrics?!
    I need to keep track of the upper left corner of the text/image, as well as the width/height of it. This will be recorded in a file.
    The text/images need to smoothly move around the panel as the mouse drags when selectin an entity.. not just "click the entity, then click another point and the entity appears there as if by magic...":)
    Please, tell the best way to do that!
    Thanks everybody!
    Message was edited by:
    cassio.marques

    I know what you mean! This happened to me as well!
    And one thing that I found useful is, if you want to directly select a layer without selecting from the layers pallete and without having autoselect enabled, just hold Ctrl and click on in directly in the image. This saved me a lot of time!

  • Displaying image in JPanel and scroll it through JScrollpanel

    Can any one will help me,
    I need to draw a image in a JPanel and, this JPanel is attached with a Jscrollpanel.
    I need to scroll the this JPanel to view the image.

    Here is my code for that
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PicPanel extends javax.swing.JPanel implements WindowListener{
    /** Creates new form PicPanel */
    public PicPanel() {
    initComponents();
    // this.setOpaque(true);
    JFrame myFrame = new JFrame("Panel Tiler");
    myFrame.addWindowListener( this );
    myFrame.setSize(new Dimension(1000,300));
    setPreferredSize(new Dimension(1000,300));
    Container cp = myFrame.getContentPane();
    cp.add( this, BorderLayout.CENTER );
    tk = Toolkit.getDefaultToolkit();
    im =tk.getImage("smple.jpg");
         jPanel1.im=im;
    // jPanel1.setSize(new Dimension(1000,300));
    myFrame.pack();
    myFrame.show();
    jPanel1.repaint();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
         jPanel1=new JPanelC();
    jScrollPane1 = new javax.swing.JScrollPane(jPanel1);
    setLayout(new java.awt.GridBagLayout());
    jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setOpaque(false);
         gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 378;
    gridBagConstraints.ipady = 298;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.ipadx = 372;
    gridBagConstraints.ipady = 280;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jPanel1, gridBagConstraints);
    public static void main(String[] args)
    new PicPanel();
    public void windowOpened(WindowEvent e) {}
    public void windowClosing(WindowEvent e)
    // myFrame.dispose();
    System.exit(0);
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    private JPanelC jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private Icon iiBackground;
    private Toolkit tk;
    private Image im;
    class JPanelC extends javax.swing.JPanel{
    public Image im;
    public void paintComponent(Graphics g){
              //super.paintComponent(g);
    if(im!=null)
                   imageobserver io = new imageobserver();
         System.out.println(im.getHeight(io));
         if(im.getHeight(io)!=-1)
    setSize(im.getWidth(io), im.getHeight(io));
    g.drawImage(im,0,0,null);
         // setOpaque(false);
    super.paintComponent(g);
    class imageobserver implements java.awt.image.ImageObserver{
    public boolean imageUpdate(Image img, int infoflags, int x, int y,int width, int height) {
              if ((infoflags & java.awt.image.ImageObserver.ALLBITS) != 0) {
    repaint();
    return false;
    //repaint();
    return true;
    Here i need to scroll the image in the panel but it is not working out.

  • Canvas3D JPanel and Behavior

    Hello,
    I am a student’s geomatic and I do my memory on 3D object implementation in a data base.
    To do that, I have a 3D graphic interface. I use Java 3D and Swing.
    Now, my program load only 3D points. There are 3 parts:
    - a 3D viewer,
    - a table,
    - buttons for the actions.
    I would like to get the 3D mouse coordinates in my 3D world.
    I succeed in a first program’s version. There were two windows JFrame, one included the Canevas3D and the other the table with the buttons.
    For the mouse’s action, I modify this source code :
    http://deven3d.free.fr/telechargements/fichiers/java3d/chap07/SimpleBehavior/SimpleBehavior.java
    Then, I put the Canevas3D in a JPanel (and neither in a separate window). And I add this JPanel to the JFram (those contain the table and the buttons for the actions).
    And after that my class Behavior don’t work.
    I think it’s due to my ActionListener (it’s use to catch the buttons’ press) who intercept the mouse action.
    This is my class Behavior :
    import java.awt.AWTEvent;
    import java.awt.Point;
    import java.awt.event.*;
    import java.util.Enumeration;
    import javax.media.j3d.*;
    import javax.vecmath.Point3d;
    public class InterGraph3d extends Behavior {
           // Condition qui va declencher le stimulus
           private WakeupCondition wakeupCondition =
                new WakeupOnAWTEvent(MouseEvent.MOUSE_PRESSED);
           private Canvas3D caneva;
           InterGraph3d (Canvas3D cane){
                   this.caneva = cane;
         public void initialize() {
             this.wakeupOn(wakeupCondition);
         public void processStimulus(Enumeration criteria) {
              WakeupCriterion critere;
             AWTEvent[] events;
             MouseEvent evt;
             // On boucle sur les critères ayant declenche le comportement
             while (criteria.hasMoreElements()) {
               // On recupere le premier critere de l'enumeration
               critere = (WakeupCriterion)criteria.nextElement();
               // On ne traite que les criteres correspondant a un evenement AWT
               if (critere instanceof WakeupOnAWTEvent) {
                 // On récupère le tableau des evements AWT correspondant au critere
                 events = ((WakeupOnAWTEvent)critere).getAWTEvent();
                 if (events.length > 0) {
                   // On récupère l'événement
                   evt = (MouseEvent)events[events.length-1];
                   // Traitement au cas par cas selon la touche pressée
                   switch(evt.getButton()) {
                   // Obtenir les coordonnées 3D du point cliqué
                     case MouseEvent.BUTTON1: // clic gauche
                     // pour avoir les coordonnées du point cliqué dans l'univers en 3D
                     // on déclare un point 3D
                     Point3d ptSourie = new Point3d();
                     // on utilise la fonction pour avoir les coordonnées de la sourie en 3D.
                     ptSourie = obtenirPointSourieCaneva(caneva, evt.getPoint());
                     // ici faire une liaison avec l'interface graphique
                     System.out.println("Coor sourie");
                       System.out.println(ptSourie.x);
                       System.out.println(ptSourie.y);
                       System.out.println(ptSourie.z);
                       break;
              // Une fois le stimulus traite, on réinitialise le comportement
             this.wakeupOn(wakeupCondition);
         // fonction pour récupérer les coordonnées de la sourie dans le
         public Point3d obtenirPointSourieCaneva(Canvas3D myCanvas, Point clickPos)
              Point3d mousePos = new Point3d();
              //pixel value in image-plate coordinates and copies that value into the object provided.
             myCanvas.getPixelLocationInImagePlate(clickPos.x, clickPos.y, mousePos);
              //This block of code converts our image plate coordinates out to virtual world coordinates
              Transform3D motion = new Transform3D();
              myCanvas.getImagePlateToVworld(motion);
              //We do this convertion the mouse position.
              motion.transform(mousePos);
              return mousePos;
    }

    The ScrollDemo uses the column and row header as well as the corner to create the rulerIt adds a component to the colum and row header and the corner. That component may or may not be a JPanel, or JComponent which they have used for custom painting.
    Can I change the ScrollDemo to use a JPanel instead?Makes no sense. There are 9 areas to add a Component. Any of those 9 areas can hold a JPanel.
    Does a JPanel provide the same elements A panel uses a LayoutManager to place components. Check the scroll pane source code to see what LayoutManager it uses.

  • Semi transparent models, using a greyscale image

    Hi,
    Ive done a few searches on the forum for this. But couldnt
    find a specific answer. With regards to textures with alpha
    channels, and im not sure if im aiming in the right direction.
    I want to have a semi transparent model, of a hair model
    actually. I have a grayscale image, which is the alpha channel
    information, and i have a number of textures of various hair
    colours that work with this greyscale alpha jpg.
    I'd like to assign the alpha channel jpg to textureList[1],
    to ahieve transparency according to the greyscale image. then apply
    the specific hair colour jpg to textureList[2].
    Ive played around with blend, blendSource and blendConstant,
    and I can get a bit of an effect(streaks in the girls hair), but
    not the alpha channel effecting the visibility of the model effect
    i'm after.
    Is it possible to affect the visibility of a models polys,
    through a greyscale texture/jpg being used for alpha channel
    information? Is there another way, that ive missed?
    Thanks in advance,
    Glenno

    You could even animate the alpha of the image using imaging
    lingo. To set it on a single #fromImageObject texture you will need
    to create two images, a 32 bit "host" image and an 8 bit grayscale
    image. You can then use setAlpha() to apply the alpha information
    to your host image and then create the texture using the 32 bit
    imageobject (with the correct texturerenderformat). If either the
    host imageobject is not 32 bit or the grayscale image not 8 bit the
    setAlpha() operation will fail silently.

Maybe you are looking for

  • My ITunes wont start.

    Everytime i try to start ITunes, a message appears saying that ITunes closed itself. I have downloaded the newest version, and I use a Macbook pro Here is what it says..... Process:         iTunes [643] Path:            /Applications/iTunes.app/Conte

  • Has anyone tried editing an iWeb site with Contribute or Dreamweaver?

    Before iWeb, I liked using Adobe Macromedia Contribute to edit the.Mac homepages. I've been giving iWeb a spin, and it seems to occupy the same place in Apple's stable as the rest of its siblings - a pre-pubescent version of Contribute, which is a su

  • MC container causes this code to fail...why ?

    Hi Flash CS5 as3 We have settlements named with suffix _Level2 such as e.g. Mitre'sGate_Level2 as well as _Level3 as MovieClips that are in a container MovieClip called Map_Collection. The code below fails with the error shown if the code line shown

  • HT4045 21.4 2012 how do i import cd to itunes

    How do i import a CD to itunes when there is no slot to input a CD??

  • ORACLE 11g R2 POST Install Issue

    Hi, I have successfully installed ORACLE 11g R2 on my windows 7 platform. The problem is that when i open the database control URL page and then enter my credentials, it fails to log in and says that an internal error has occurred. Please view the lo