JPanel setOpaque(false) isn't transparent ?

Hi,
I've set a JPanel as the only thing added to a JFrame container. I've set a picture to this JPanel by using the following code
          JPanel temp = new JPanel()
               public void paintComponent(Graphics g)
                     Dimension d = getSize();
                     g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                    setOpaque( false );
                    super.paintComponent(g);
          };Now I've added another JPanel onto this one. I've set its background to RED, so there is a red square over my picture on my JFrame. However I want this JPanel to be fully transparent, so you can't actually see it at all, so the picture behind it on the original JPanel shows through.
But when I use setOpaque(false), I just get a gray square instead of a red one, it doesn't show anything through at all.
Anyone know why this would be ?
Thanks

Here you go, the background picture is not shining through. You'll have to change the jpg name to whatever you want to use.
Thanks
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class OneToOneChat extends JFrame
     protected JPanel leftZone, rightZone, totalZone;
     protected JTextPane bottomLeftZone, topLeftZone;
     protected JScrollPane topScroll, bottomScroll;
     public static void main(String args[])
          new OneToOneChat();          
     public OneToOneChat()
          setSize(400,400);          
          setTitle("My Opaque Problem");
          setLocation(200,200);
          setResizable(false);     
          Container con = getContentPane();
          leftZone = new JPanel(new BorderLayout());
          rightZone = new JPanel(new BorderLayout());          
          totalZone = new JPanel(new BorderLayout());               
          topLeftZone = new JTextPane();                              
          bottomLeftZone = new JTextPane();     
          topScroll = new JScrollPane(topLeftZone, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);          
                topScroll.setPreferredSize(new Dimension(250,150));          
          bottomScroll = new JScrollPane(bottomLeftZone,
                                       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                       JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                      
          bottomScroll.setPreferredSize(new Dimension(250,150));                                      
          rightZone.setOpaque(false);          
          rightZone.setBackground(Color.RED);          
          rightZone.setBorder( new LineBorder(Color.GREEN) );          
          rightZone.setPreferredSize(new Dimension(250,300));                                             
          leftZone.add(topScroll, "North");
          leftZone.add(bottomScroll,"South");
          totalZone.add(leftZone,"West");
          totalZone.add(rightZone,"East");
          final ImageIcon icon = new ImageIcon("ripple.jpg");                    
          JPanel temp = new JPanel()
               public void paintComponent(Graphics g)
                    Dimension d = getSize();
                    g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                    setOpaque( false );
                    super.paintComponent(g);
          temp.setBorder(new EmptyBorder(8,8,8,8));                    
          temp.add(totalZone);                                             
          con.add(temp);     
          pack();
          setVisible(true);
}

Similar Messages

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • SetOpaque(false) doesn't work

    Hi,
    I'm looking for help to have background transparent panels. I tried to use JPanel with setOpaque(false), but I still have a lightGrey background ! Is it normal ??? I don't think so. Could anyone help me please...

    Thanks for your answers.
    I get rid of JComponent, I prefer not to use Swing for my application.
    So I will ask another question. I still want transparent panels and labels but in AWT. I found code to make them transparent, but when I draw an image on the last panel (in the background), I have the trace of the panels and labels which are above, and their backgrounds have the same color than the panel on which I draw my image.
    I DON'T UNDERSTAND !!!
    I'm looking for a solution to have a background image in my labels, but I have the text or the background, never both, even using drawString instead of label constructor.
    An idea ?
    Excuse my English, I'm French. :0�

  • Why does setOpaque(false) on Mac interfere with functionality of JSlider?

    Hello, here is an SSCCE with a slider that works normally on my PC:
    import javax.swing.*;
    public class Foobar extends JApplet
         public  void init()
              JPanel panel = new JPanel();
              panel.setOpaque(false);
              panel.add(new JSlider());
              setContentPane(panel); 
    }But on my sister's Mac, the slider functionality is broken: one cannot drag the thumb with the mouse. To move the thumb, she has to click on the rail. If I comment out the setOpaque(false) call, then everything works fine.
    I need that setOpaque call and I want the program to work both on Mac and PC. Why does it break on the Mac and how to fix it? Thank you for your insight. Mark

    So then you haven't actually ran that SSCCE on a MAC then? No, no, she ran it on her Mac, my sis. I asked her to run it several times, and she definitely cannot move the thumb. Now, if I comment out the setOpaque(false), then she can move it all right.
    But, I found a workaround. I did not realize that before, that Apple actually does include the "cross-platform" look and feel, not only their own Aqua. On the Sun website, it sort of implies that Apple only has Aqua, but on Apple website, I found they also support the cross-platform look.
    And voila, I changed to the cross-platform, and now, everything works. Not only the sliders in non-opaque panels, but I had also a HUGE number of other problems getting my app to work on the Mac, and now, with the cross-platform look, they all disappeared!!
    Thank you.
    Mark

  • JPopupMenu ignores setOpaque(false) near screen edges

    Dear group
    I try to paint a custom JPopupMenu with transparency, but this is ignored when the popup is opened so it overlaps near screen edges (bottom and right side). This is also the case if the popup overlaps the Microsoft Windows toolbar at the bottom.
    I may be able to emulate JPopupMenus using custom components in a JLayeredPane, but can anyone explain the above behaviour?
    Thanks and Best Regards,
    Aksel, Denmark
    Environment: j2sdk-se 1.6.0_10 and windows xp
    Example:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPopupMenu;
    public class TransparencyPopupNearBorderTest {
    public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setBounds(new Rectangle(screenSize));
    frame.setUndecorated(true);
    frame.setPreferredSize(screenSize);
    frame.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseReleased(MouseEvent e) {
    JPopupMenu popup = new JPopupMenu();
    popup.setOpaque(false);
    JLabel label = new JLabel("TRANSPARENT");
    label.setFont(new Font("Helvetica", Font.PLAIN, 42));
    popup.add(label);
    popup.setLightWeightPopupEnabled(false);
    popup.show(frame, e.getX(), e.getY());
    frame.getContentPane().setBackground(Color.BLUE);
    frame.pack();
    frame.setVisible(true);
    }

    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    I don't know if transparency painting has changed in 1.6.0_10. Prior to that I believe transparency can only be achieved in lightweight components (ie. Swing does all the painting). JFrame, JWindow and JDialog are not lightweight because they use OS components.
    In the case of a popup, it is lightweight when entirely contained within its parent frame. But a lightweight popup can not be painted outside the bounds of the frame so a JWindow (I believe) is used as the popup, which can't be transparent.

  • Extending DefaultTreeCellRenderer, Jlabel setOpaque(false) no effect

    Hi, im using the code below, but my JLabel component.setOpaque(false) is having no effect, is this possible?
    private class MyRenderer extends DefaultTreeCellRenderer {
                ImageIcon tabIconOnline, tabIconOffline;
                String status;
                public MyRenderer() {
                public Component getTreeCellRendererComponent(
                        JTree tree,
                        Object value,
                        boolean sel,
                        boolean expanded,
                        boolean leaf,
                        int row,
                        boolean hasFocus) {
                    JLabel jl = (JLabel)super.getTreeCellRendererComponent(
                            tree, value, sel,
                            expanded, leaf, row,
                            hasFocus);
                                     jl.setOpaque(false); // not working
                    setOpaque(false); // not working
                    tree.setOpaque(false); // not working
                                     setBackgroundSelectionColor(MyGUI.ITEM_SELECTION_COLOUR);
                    setBackgroundNonSelectionColor(null);  // not working
                    setBorderSelectionColor(new Color(10, 10, 255));
                    return jl;
        }

    heres the full code, im using:
            private class MyRenderer extends DefaultTreeCellRenderer {
                ImageIcon tabIconOnline, tabIconOffline;
                String status;
                public MyRenderer() {
                public Component getTreeCellRendererComponent(
                        JTree tree,
                        Object value,
                        boolean sel,
                        boolean expanded,
                        boolean leaf,
                        int row,
                        boolean hasFocus) {
                    JLabel jl = (JLabel)super.getTreeCellRendererComponent(
                            tree, value, sel,
                            expanded, leaf, row,
                            hasFocus);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
                    //jl.setOpaque(false);
                   // setOpaque(false);
                    tree.setOpaque(false);
                    if (node == rootNode) {
                        setForeground(new Color(255, 255, 255));
                    } else if ((node == nodeFriends) ||(node == nodeRecent)||(node == nodeIgnored)) {
                        if (leaf) {
                            setIcon(createImageIcon("images/icon_noChildren.gif"));
                        setForeground(new Color(255, 255, 255));
                        setToolTipText("To add a Friend , Right click then 'Add A Friend'");
                    } else if (node.getParent() == nodeFriends) {
                        Friend friend = (Friend)(node.getUserObject());
                        if (friend.getStatus().equals("online")) {
                            setForeground(new Color(255, 255, 255));
                            setIcon(createImageIcon("images/icon_online.gif"));
                            setToolTipText("Is " + friend.getStatus());
                        } else {
                            setIcon(createImageIcon("images/icon_offline.gif"));
                            setToolTipText("Is " + friend.getStatus());
                            setForeground(new Color(255, 255, 255));
                    } else if (node.getParent() == nodeRecent) {
                        setForeground(new Color(255, 255, 255));
                    } else if (node.getParent() == nodeIgnored) {
                        setForeground(new Color(255, 255, 255));
                        setToolTipText("You are ignoring this user");
                    if (sel) {
                        setForeground(Color.black);
                    //jl.setBackground(null);
                    setBackgroundSelectionColor(MyGUI.ITEM_SELECTION_COLOUR);
                    //setBackgroundNonSelectionColor(null);
                    setBorderSelectionColor(new Color(10, 10, 255));
                    return jl;
        }

  • My control center isn't transparent...      Why??

    I want to know why my controll center isn't transparent??

    My Control Center is annoyingly slightly transparent. I wish it was just solid. How much transparency do you want?

  • My iPhone 5c lock screen isn't transparent

    it's hard to explain without a picture, but whenever I unlock my iPhone 5c the screen where you enter the passcode isn't transparent. it is also meant to be transparent when you drag up the lower menu bar of the screen, but it isn't. this has nothing to do with how my iPhone is working but it bothers me knowing that it's not as pretty and other 5c's don't have the same problem.

    Settings > General > Accessibility > Increase Contrast : OFF > Reduce Transparency: OFF

  • [Solved] KDE 4.10: The taskbar isn't transparent any more

    Hi,
    after the upgrade from KDE 4.9 to KDE 4.10 I noticed, that the taskbar isn't transparent any more.
    So, up to now I couldn't find the settings to change that, that's why I just want to ask how I can get back the taskbar transparency?
    Thanks in advance for your help.
    Last edited by maik-hro (2013-02-08 18:08:07)

    Same: opengl is broken, even crashes kwin on start up. Only xrender compositing is working now. Even starting a new .kde4 folder hasn't fixed it. I guarantee it's f#@* Catalyst again.
    Last edited by 12eason (2013-02-09 19:55:34)

  • SetOpaque(false);

    Hello:
    I have got your code on how to set a background image. Thank you so much.
    But I have another question , my question is that
    what is the purpose of the following method
    setOpaque(false);
    and also this method belongs to which class?

    DON'T CREATE A NEW THREAD EACH TIME YOU REPLY.
    THE REPLY BUTTON IS LOCATED AT THE UPPER RIGHT CORNER.
    REPLY TO THIS THREAD.
    http://forum.java.sun.com/thread.jspa?threadID=5223082&tstart=0

  • My iPod Touch 5G isn't transparent

    Notification and control centers used to be transparent, but they stopped being transparent after the new iOS update came out, is it suppose to be like that or is there a setting that I'm missing?

    If you are developer, use those credentials to log into the private developer forum, not here in the public forum.

  • Transparent JSpinner

    Hi!
    I'm trying to create a transparent JSpinner on top of a JPanel with an image as background. Apparently setOpaque(false) isn't enough to acheive this and so I'm wondering if there's another way to do it. Can I override some paint method for the JFormattedTextField or customize some UI class?
    Any help appreciated!

    Thanks for your reply!
    Here's a short example:
    import java.awt.Graphics;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    public class SpinnerTest extends JFrame {
      String background = "bkg.jpg";
      public SpinnerTest() {
        ImageIcon imageIcon = new ImageIcon(background);
        setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight());
        JPanel panel = new JPanel() {
          public void paintComponent(Graphics g) {
            g.drawImage(new ImageIcon(background).getImage(), 0, 0, null);
        panel.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight());
        JSpinner spinner = new JSpinner();
        spinner.setOpaque(false);
        panel.add(spinner);
        getContentPane().add(panel);
      public static void main(String[] args) {
        new SpinnerTest().setVisible(true);
    } What I would like to see is the JPanel background bkg.jpg through the JSpinner.

  • In Need Of Divine Intervention

    Need some help with this. I can't seem to get the "browse" button to browse my PC for images in the Upload frame. The "Cancel" button is closing the entire programme instead of just the Upload frame.
    Anyone know the problem? i just started java bout 3 months ago and still a noob at it =(
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.List;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.FileImageInputStream;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class PhotoAlbum extends JFrame
      implements ActionListener
      // Menu items Upload, Save, exit, and About
      private JMenuItem jmiUpload, jmiSave,jmiExit, jmiAbout, ttUpload;
      private JButton jbtnEditlabel , jbtnSavelabel,browse,cancel;
      // Text area for displaying and editing text files
         private JPanel jta,over;
         Image image;     
         SlidePanel slidePanel;     
         JComboBox slides;
         JFrame f;
         JFileChooser fileChooser;
      // Status label for displaying operation status
      private JLabel jlblStatus = new JLabel();
      // Scrolling
      private JScrollPane scrollPane = new JScrollPane();
      // File dialog box
      private JFileChooser jFileChooser = new JFileChooser();
      // Radio Buttons
      private JRadioButtonMenuItem jmiSlideshow , jmiThumbnail;
      //JPanels
      private JPanel head , body , low;
      /**Main method*/
      public static void main(String[] args)
           JFrame.setDefaultLookAndFeelDecorated(true);
        PhotoAlbum frame = new PhotoAlbum();
        frame.setSize(600, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         frame.setLocationRelativeTo( null );
      public PhotoAlbum()
        setTitle("Photo Library");
        // Create a menu bar mb and attach to the frame
        JMenuBar mb = new JMenuBar();
        setJMenuBar(mb);
        // Add a "File","Help" and "View" menu in mb
        JMenu fileMenu = new JMenu("File");
        mb.add(fileMenu);
        JMenu viewMenu = new JMenu("View");
         mb.add(viewMenu);
         JMenu helpMenu = new JMenu("Help");
         mb.add(helpMenu);
              JPanel jta = new JPanel();
         //Setting a scrolling pane for jta
         jta.setOpaque( false );//making jta transparent
         jta.setPreferredSize( new Dimension(1200, 1200) );
        // Create and add menu items to the menu
        fileMenu.add(ttUpload = new JMenuItem("Upload"));
        fileMenu.add(jmiSave = new JMenuItem("Save"));
        fileMenu.addSeparator();
        fileMenu.add(jmiExit = new JMenuItem("Exit"));
        helpMenu.add(jmiAbout = new JMenuItem("About"));
    //    group.add(jmiThumbnail);group.add(jmiSlideshow);
        viewMenu.add(jmiThumbnail = new JRadioButtonMenuItem("Thumbnail"));
        viewMenu.add(jmiSlideshow = new JRadioButtonMenuItem("Slideshow"));
        getContentPane().add(scrollPane);
         //  "Low Panel"with a white background and placing "jbtnEditlabel" into it
         low = new JPanel();
         low.setBackground(Color.white);
         low.add(jbtnEditlabel = new JButton("Edit Labels"));
         //  "Low Panel     
         body = new JPanel();
         jta.setBackground(Color.white);
         // Creating edit label button
         getContentPane().add(low, BorderLayout.SOUTH);
        // Set default directory to the current directory
        jFileChooser.setCurrentDirectory(new File("."));
        // Set BorderLayout for the frame
        getContentPane().add(new JScrollPane(jta),BorderLayout.CENTER);
        getContentPane().add(jlblStatus, BorderLayout.NORTH);
        // Register listeners
        ttUpload.addActionListener(this);
        jmiSave.addActionListener(this);
        jmiAbout.addActionListener(this);
        jmiExit.addActionListener(this);
        jmiSlideshow.addActionListener(this);
        jmiThumbnail.addActionListener(this);
        jbtnEditlabel.addActionListener(this);
      /**Handle ActionEvent for menu items*/
      public void actionPerformed(ActionEvent e)
        String actionCommand = e.getActionCommand();
        if (e.getSource() instanceof JMenuItem)
          if ("Upload".equals(actionCommand))
            upload();
          else if ("Save".equals(actionCommand))
            save();
          else if ("About".equals(actionCommand))
            JOptionPane.showMessageDialog(this,"Insert Images using Upload or edit the labels of present images.",
            "About This Demo",JOptionPane.INFORMATION_MESSAGE);
          else if ("Exit".equals(actionCommand))
            System.exit(0);
          else if ("Slideshow".equals(actionCommand))
            jmiSlideshow();       
          else if ("Thumbnail".equals(actionCommand))
            jmiThumbnail();
      /**Save file*/
      private void save()
        if (jFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
          save(jFileChooser.getSelectedFile());
      /**Save file with specified File instance*/
      private void save(File file)
        try
          // Write the text in jta to the specified file
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    //      byte[] b = (jta.getText()).getBytes();
    //      out.write(b, 0, b.length);
          out.close();
          // Display the status of the save file operation in jlblStatus
          jlblStatus.setText(file.getName()  + " Saved ");
        catch (IOException ex)
          jlblStatus.setText("Error saving " + file.getName());
         /**jmiSlideshow file*/
      private void jmiSlideshow()
      /**jmiThumbnail file*/
      private void jmiThumbnail()
            private void upload()
                   /* Set title of frame to Upload File*/
                   String frameTitle="Upload File";
                   final JFrame upload= new JFrame(frameTitle);
                   /* Creating "file" label / txtfield and uploadPanel */
                   JPanel uploadPanel=new JPanel();
                   JLabel xfile=new JLabel("File");
                   JTextField input=new JTextField(20);
                   /* Creating buttons and btm panel*/
                   JPanel  buttonPanel=new JPanel();
                   JButton jbtnCancel=new JButton("Cancel");
                   JButton jbtnOk=new JButton("OK");
                   JButton jbtnBrowse=new JButton("Browse");
                   /* Adding buttons and txtfields into uploadPanel*/
                   uploadPanel.add(xfile);
                   uploadPanel.add(input);
                   uploadPanel.add(jbtnBrowse);               
                   uploadPanel.add(jbtnCancel);
                   uploadPanel.add(jbtnOk);
                   /* Adding uploadPanel into upload*/
                   upload.getContentPane().add(uploadPanel);
                   /* Set size/visibilty/ and close operations*/
                   upload.setSize(550, 200);
                   upload.setVisible(true);
                   upload.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   upload.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             upload.setVisible(false);
                   /* Adding listeners for the buttons in Upload()*/
                   jbtnCancel.addActionListener(new jbtnCancelListener());          
                   jbtnBrowse.addActionListener(new jbtnBrowseListener());
          /* Cancel button */
               class jbtnCancelListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit(0);
          /**Browse button*/
               class jbtnBrowseListener implements ActionListener
              public void actionPerformed(ActionEvent e)
              if(fileChooser.showOpenDialog(f) == JFileChooser.APPROVE_OPTION)
                File file = fileChooser.getSelectedFile();
                     if(hasValidExtension(file))
                    Slide slide = new Slide(file);
                    slides.addItem(slide);
                    slides.setSelectedItem(slide);
                    slidePanel.addImage(slide.getFile());
             public boolean hasValidExtension(File file)
                 String[] okayExtensions = { "gif", "jpg", "png" };
                 String path = file.getPath();
                 String ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
                 for(int j = 0; j < okayExtensions.length; j++)
                if(ext.equals(okayExtensions[j]))
                return true;
                 return false;
         class Slide
        File file;
        public Slide(File file)
            this.file = file;
        public File getFile()
            return file;
        public String toString()
            return file.getName();
    class SlidePanel extends JPanel
        List<BufferedImage> images;
        int count;
        boolean keepRunning;
        Thread animator;
        public SlidePanel()
            images = Collections.synchronizedList(new ArrayList<BufferedImage>());
            count = 0;
            keepRunning = false;
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            if(images.size() > 0)
                BufferedImage image = images.get(count);
                int imageWidth = image.getWidth();
                int imageHeight = image.getHeight();
                int x = (w - imageWidth)/2;
                int y = (h - imageHeight)/2;
                g.drawImage(image, x, y, this);
        private Runnable animate = new Runnable()
            public void run()
                while(keepRunning)
                    if(images.size() == 0)
                        stop();
                        break;
                    count = (count + 1) % images.size();
                    repaint();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("animate interrupt: " + ie.getMessage());
                repaint();
        public void start()
            if(!keepRunning)
                keepRunning = true;
                animator = new Thread(animate);
                animator.start();
        public void stop()
            if(keepRunning)
                keepRunning = false;
                animator = null;
        public void addImage(File file)
            try
                FileImageInputStream fiis = new FileImageInputStream(file);
                images.add(ImageIO.read(fiis));                             
            catch(FileNotFoundException fnfe)
                System.err.println("file: " + fnfe.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
        public void removeImage(int index)
            images.remove(index);
    }

    not got time to look much but replace the System.exit(0) with this.dispose() will close the frame instead of closing the whole application.
    http://www.magiksafe.com

  • Problem repainting Jframe  (i think)

    import javax.swing.*;*
    *import java.awt.*;
    import java.awt.event.*;*
    *import javax.swing.border.*;
    class Example extends JFrame implements ActionListener{
    JPanel basicPanel;
        JPanel panel1;
         ButtonGroup gramatici;
         JRadioButton gramatica1;
        JRadioButton gramatica2;
        JRadioButton gramatica3;
        JRadioButton gramatica4;
        JRadioButton gramatica5;
        JRadioButton gramatica6;
        JRadioButton gramatica7;
        JRadioButton gramatica8;
        JRadioButton gramatica9;
        JRadioButton gramatica10;
        JRadioButton gramatica11;
        JRadioButton gramatica12;
        ImageIcon img;
        public Example(){
             super("example");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             img = new ImageIcon("anyImage.jpg");
             setSize(img.getIconWidth(),img.getIconHeight()); //setting Frame size = to JPG rez
              setResizable(false);
              basicPanel = new JPanel(){
                   protected void paintComponent(Graphics g)
                        //paint full img rez
                        g.drawImage(img.getImage(), 0, 0, null);
                        super.paintComponent(g);
              basicPanel.setLayout(null);
              Color transparent =new Color(104,185,234,85);
              panel1 =new  JPanel();
              panel1.setBackground(transparent);
              panel1.setLayout(null);
              gramatici =new ButtonGroup();
              gramatica1 = new JRadioButton();
            gramatica2 = new JRadioButton();
            gramatica3 = new JRadioButton();
            gramatica4 = new JRadioButton();
            gramatica5 = new JRadioButton();
            gramatica6 = new JRadioButton();
            gramatica7 = new JRadioButton();
            gramatica8 = new JRadioButton();
            gramatica9 = new JRadioButton();
            gramatica10 = new JRadioButton();
            gramatica11 = new JRadioButton();
            gramatica12 = new JRadioButton();
            gramatici.add(gramatica1);
            gramatici.add(gramatica2);
            gramatici.add(gramatica3);
            gramatici.add(gramatica4);
            gramatici.add(gramatica5);
            gramatici.add(gramatica6);
            gramatici.add(gramatica7);
            gramatici.add(gramatica8);
            gramatici.add(gramatica9);
            gramatici.add(gramatica10);
            gramatici.add(gramatica11);
            gramatici.add(gramatica12);
            gramatica1.setText("Blablabla 1");
            gramatica1.setBounds(10,10,130,20);
            gramatica2.setText("Blablabla 2");
            gramatica2.setBounds(10,30,130,20);
            gramatica3.setText("Blablabla 3");
            gramatica3.setBounds(10,50,130,20);
            gramatica4.setText("Blablabla 4");
            gramatica4.setBounds(10,70,130,20);
            gramatica5.setText("Blablabla 5");
            gramatica5.setBounds(10,90,130,20);
            gramatica6.setText("Blablabla 6");
            gramatica6.setBounds(10,110,130,20);
            gramatica7.setText("Blablabla 7");
            gramatica7.setBounds(10,130,130,20);
            gramatica8.setText("Blablabla 8");
            gramatica8.setBounds(10,150,130,20);
            gramatica9.setText("Blablabla 9");
            gramatica9.setBounds(10,170,130,20);
            gramatica10.setText("Blablabla 10");
            gramatica10.setBounds(10,190,130,20);
            gramatica11.setText("Blablabla 11");
            gramatica11.setBounds(10,210,130,20);
            gramatica12.setText("Blablabla 12");
            gramatica12.setBounds(10,230,130,20);
            gramatica1.setOpaque(false);
            gramatica2.setOpaque(false);
            gramatica3.setOpaque(false);
            gramatica4.setOpaque(false);      //make them transparent
            gramatica5.setOpaque(false);
            gramatica6.setOpaque(false);
            gramatica7.setOpaque(false);
            gramatica8.setOpaque(false);
            gramatica9.setOpaque(false);
            gramatica10.setOpaque(false);
            gramatica11.setOpaque(false);
            gramatica12.setOpaque(false);
            gramatica1.setRolloverEnabled(false);
            gramatica2.setRolloverEnabled(false);
            gramatica3.setRolloverEnabled(false);
            gramatica4.setRolloverEnabled(false);     
            gramatica5.setRolloverEnabled(false);
            gramatica6.setRolloverEnabled(false);
            gramatica7.setRolloverEnabled(false);
            gramatica8.setRolloverEnabled(false);
            gramatica9.setRolloverEnabled(false);
            gramatica10.setRolloverEnabled(false);
            gramatica11.setRolloverEnabled(false);
            gramatica12.setRolloverEnabled(false);
            gramatica1.addActionListener(this);
            gramatica2.addActionListener(this);
            gramatica3.addActionListener(this);
            gramatica4.addActionListener(this);
            gramatica5.addActionListener(this);
            gramatica6.addActionListener(this);
            gramatica7.addActionListener(this);
            gramatica8.addActionListener(this);
            gramatica9.addActionListener(this);
            gramatica10.addActionListener(this);
            gramatica11.addActionListener(this);
            gramatica12.addActionListener(this);
            panel1.add(gramatica1);
            panel1.add(gramatica2);
            panel1.add(gramatica3);
            panel1.add(gramatica4);
            panel1.add(gramatica5);
            panel1.add(gramatica6);
            panel1.add(gramatica7);
            panel1.add(gramatica8);
            panel1.add(gramatica9);
            panel1.add(gramatica10);
            panel1.add(gramatica11);
            panel1.add(gramatica12);
            panel1.setSize((img.getIconWidth()/2)-200,
            (img.getIconWidth()/2)-60); // set panel size based on frame res (JPG -resolution)
            panel1.setBorder(new BevelBorder (BevelBorder.RAISED));
            panel1.setLocation((img.getIconWidth()/2)-panel1.getWidth()/2,//set panel to center based on Frame res.
            (img.getIconHeight()/2)-panel1.getHeight()/2);              // works with JPG img. of 800 x 600, didn't try other resolution to see.
            basicPanel.add(panel1);
            getContentPane().add(basicPanel, BorderLayout.CENTER);
            basicPanel.setOpaque( false );
            Dimension rezolutie =new Dimension(img.getIconWidth(),img.getIconHeight());
              basicPanel.setPreferredSize(rezolutie);
              basicPanel.repaint();
               pack();
            setVisible(true);
        public void actionPerformed ( ActionEvent e ) {          //<-- This seems to solve part of problem...
        String command = e.getActionCommand ();                    
        if  (command.equals ("Blablabla 1")) {
             basicPanel.repaint();                                   // without repainting the IMG panel      
             }                                                                 //all buttons remain selected (i don't know why).
         if  (command.equals ("Blablabla 2")) {                    
             basicPanel.repaint();                         
             if  (command.equals ("Blablabla 3")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 4")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 5")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 6")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 7")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 8")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 9")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 10")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 11")) {
             basicPanel.repaint();
             if  (command.equals ("Blablabla 12")) {
             basicPanel.repaint();
        public static void main (String[] args) {
        new Example();
    }

    I took Encephelo's code and altered it quite a bit - see if this works for you - it does use a listener ...
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    public class Example2 {
      private static final String IMAGE_PATH = "DCP_2143.JPG";
      private static final int BUTTON_COUNT = 12;
      private JRadioButton[] jrbs;
      private static Color TRANSPARENT = new Color(104, 185, 234, 85);
      private JFrame frame;
      private JPanel mainPanel;
      private JPanel innerPanel;
      private Image image;
      ButtonGroup gramatici;
      public Example2() {
        createAndShowUI();
      private void createAndShowUI() {
        JFrame frame = new JFrame("Example2");
        gramatici = new ButtonGroup();
        try {
          image = ImageIO.read(new File(IMAGE_PATH));
        } catch (IOException e) {
          e.printStackTrace();
        mainPanel = new JPanel(new GridBagLayout()) {
          protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (image != null) {
              g.drawImage(image, 0, 0, this);
        mainPanel.setPreferredSize(new Dimension(
        image.getWidth(mainPanel), image.getHeight(mainPanel)));
        innerPanel = new JPanel(new GridLayout(0, 1, 0, 10));
        innerPanel.setBackground(TRANSPARENT);
        innerPanel.setBorder(BorderFactory.createCompoundBorder(
          BorderFactory.createBevelBorder(BevelBorder.RAISED),
          BorderFactory.createEmptyBorder(25, 40, 25, 80)));
        jrbs = new JRadioButton[BUTTON_COUNT];
        for (int i = 0; i < BUTTON_COUNT; i++) {
          String text = "Radio Button " + i;
          jrbs[i] = new JRadioButton(text);
          jrbs.setActionCommand(text);
    jrbs[i].setOpaque(false);
    jrbs[i].setRolloverEnabled(false);
    jrbs[i].addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent ie) {
    mainPanel.repaint();
    gramatici.add(jrbs[i]);
    innerPanel.add(jrbs[i]);
    mainPanel.add(innerPanel);
    frame.add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Example2();

  • 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 );
    }

Maybe you are looking for

  • Exporting text from fcp

    I have a lot of separate text boxes in my sequence. Since I can' t do a spell check in fcp, I was wondering if i can export all the text boxes out as a plain text document to do a spell check. I tried exporting as a xml document, but navigating throu

  • Set funcitonal area in new PO line item

    We are trying to re-trigger the derivation of the functional area when a new PO line item is created using the <Copy PO line item> function.  Using standard SAP functionality and changing the delivery date, the functional area associated with the new

  • User logon count

    I am trying to get user logon count I am able to run a command: Get-QADUser username -properties logoncount | select logoncount and get a complete count. What if i need to get a number for a week? or a month? Thank you.

  • R3D Damaged or Unsupported File

    Hi all- I'm pretty stumped by this problem.  I have a ton of .R3D footage shot on a Scarlet.  Most of the footage imports fine into Premiere Pro CS6.0.1, but some of the files won't import.  They give me the "Damaged or Unsupported file" warning.  Wh

  • HELP!!!  Iphone 4 photos from 3Gs

    Hi any help here would be gratefully appreciated!  3 and a half years ago I purchased an IPhone 3GS and took over 300 photographs on it.  I purchased my IPhone 4 two years ago.  Synced my photos through ITunes onto my new phone and have obviously tak