Once again, I found some code that seems to be doing something that I would like to try, but I get a Static Error when I try to run the code (apparently, I may be the only one).

By the way, the code comes from the book, "Swing Hacks" By Joshua Marinacci, Chris Adamson. Credit where credit is due.

Here is the run-time error message:
Static Error: No constructor in TransparentBackground matches this invocation
Arguments: ()
Candidate signatures: TransparentBackground(JFrame)

And here is the code I am compiling and running in DrJava:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
 
 
 
public class TransparentBackground extends JComponent
  implements ComponentListener, WindowFocusListener, Runnable {
 
 // constants ---------------------------------------------------------------
 // instance ----------------------------------------------------------------
 private JFrame _frame;
 private BufferedImage _background;
 private long _lastUpdate = 0;
 private boolean _refreshRequested = true;
 private Robot _robot;
 private Rectangle _screenRect;
 private ConvolveOp _blurOp;
 
 // constructor -------------------------------------------------------------
 
 public TransparentBackground(JFrame frame) {
  _frame = frame;
  try {
   _robot = new Robot();
  } catch (AWTException e) {
   e.printStackTrace();
   return;
  }
 
  Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
  _screenRect = new Rectangle(dim.width, dim.height);
 
  float[] my_kernel = {
    0.10f, 0.10f, 0.10f,
    0.10f, 0.20f, 0.10f,
    0.10f, 0.10f, 0.10f};
  _blurOp = new ConvolveOp(new Kernel(3, 3, my_kernel));
 
  updateBackground();
  _frame.addComponentListener(this);
  _frame.addWindowFocusListener(this);
  new Thread(this).start();
 }
 
 // protected ---------------------------------------------------------------
 
 protected void updateBackground() {
  _background = _robot.createScreenCapture(_screenRect);
 }
 
 
 
 protected void refresh() {
  if (_frame.isVisible() && this.isVisible()) {
   repaint();
   _refreshRequested = true;
   _lastUpdate = System.currentTimeMillis();
  }
 }
 
 
 // JComponent --------------------------------------------------------------
 
 protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
  Point pos = this.getLocationOnScreen();
  BufferedImage buf = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
  buf.getGraphics().drawImage(_background, -pos.x, -pos.y, null);
 
  Image img = _blurOp.filter(buf, null);
  g2.drawImage(img, 0, 0, null);
  g2.setColor(new Color(255, 255, 255, 192));
  g2.fillRect(0, 0, getWidth(), getHeight());
 }
 
 // ComponentListener -------------------------------------------------------
 public void componentHidden(ComponentEvent e) {
 }
 
 public void componentMoved(ComponentEvent e) {
  repaint();
 }
 
 public void componentResized(ComponentEvent e) {
  repaint();
 
 }
 
 public void componentShown(ComponentEvent e) {
  repaint();
 }
 
 // WindowFocusListener -----------------------------------------------------
 public void windowGainedFocus(WindowEvent e) {
  refresh();
 }
 
 public void windowLostFocus(WindowEvent e) {
  refresh();
 }
 
 // Runnable ----------------------------------------------------------------
 public void run() {
  try {
   while (true) {
    Thread.sleep(100);
    long now = System.currentTimeMillis();
    if (_refreshRequested && ((now - _lastUpdate) > 1000)) {
     if (_frame.isVisible()) {
      Point location = _frame.getLocation();
      _frame.setLocation(-_frame.getWidth(), -_frame.getHeight());
      updateBackground();
      _frame.setLocation(location);
      refresh();
     }
     _lastUpdate = now;
     _refreshRequested = false;
    }
   }
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  JFrame frame = new JFrame("Transparent Window");
  TransparentBackground bg = new TransparentBackground(frame);
 
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(bg);
  frame.pack();
  frame.setSize(200, 200);
  frame.setLocation(500, 500);
  frame.setVisible(true);
 }
}

Recommended Answers

All 16 Replies

Member Avatar for coil

Well you're trying to make a new TransparentBackground by passing a JFrame, but you don't have a constructor in the class that takes a JFrame as an argument.

So either get rid of the frame argument, or create a new constructor that takes a JFrame.

Hmmm, well there is a constructor and it LOOKS like it take a JFrame to me...

public TransparentBackground(JFrame frame)

And when it gets called, a JFrame is passed into it...

JFrame frame = new JFrame("Transparent Window");
TransparentBackground bg = new TransparentBackground(frame);

Am I not understanding what you are telling me?

I get a Static Error when I try to run the code

By run the code, you mean execute it? Your code compiles ok?

Can you open a command prompt window and execute the program and copy the screen and paste it here. If you are on windows here are instructions on how to do that:
To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.

Member Avatar for coil

Never mind, I didn't see the constructor properly for some reason.

Well, I can't see anything wrong with the code, and I just compiled it myself and it works fine - I get a JFrame with a translucent background...

It could be an interaction with an IDE or some other software. Hopefully the OP will come back and explain.

By run the code, you mean execute it? Your code compiles ok?

Can you open a command prompt window and execute the program and copy the screen and paste it here. If you are on windows here are instructions on how to do that:
To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.

As I mentioned in the original post, I am using DrJava as my IDE and "normally" I use the "Compile" button to compile my code and then I use the "Run" button to run my code. If you prefer to use the term "execute", that's fine with me.

I tried "executing" the code from the command line and it seems to work nicely, which is wonderful, but it still doesn't give me a clue as to why I am getting a Static Error message when I try to "execute" the code from within DrJava, which is what I really want to accomplish here.

It could be something to do with the Robot class doing something while your IDE wants to keep control.

Why the restriction to only running the code from inside the IDE?

It could be something to do with the Robot class doing something while your IDE wants to keep control.

Why the restriction to only running the code from inside the IDE?

Its not a "restriction" as much as it is a "preference". IDEs were invented because everyone got tired of writing code in notepad, then compiling and "executing" it in a DOS window.

Nothing is changed... I prefer to write my code, compile it and "Run" it from the comfort and convenience of my IDE.

Interesting. I'd find it a bother to have to start an IDE and wait until it loads to execute any of my java programs.
To each his own.

You don't have to open a DOS window to execute a java program. I use jar files and shortcuts.

Member Avatar for coil

If it works fine command-line, then you'll probably have to go to your IDE's website and find out exactly why it's giving you an error.

I used to use that approach, but JDK 1.6u10 (or thereabouts) has REAL transparent windows. It's buries in awtutilities for now, will be fully exposed in Java 1.7
Here's a demo I wrote:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.lang.reflect.Method;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;


public class DemoWindows implements ActionListener {

   public static void main(String[] args) {
      // create a new demo, and update it every 50 mSec
      new Timer(50, new DemoWindows()).start();
   }

   int phase = 0; // demo runs a number of consecutive phases
   int count = 0; // each of which takes a number of timesteps

   JFrame window1 = new JFrame("Java windows demo");
   JLabel text1 = new JLabel("<HTML><H1>This is a demo of some of the effects"
         + "<BR>that can be achieved with the new Java"
         + "<BR>transparent window methods</H1>"
         + "<BR>(requires latest version of Java)");
   JFrame window2 = new JFrame("Java windows demo");
   JLabel text2 = new JLabel("<HTML><center>Java<BR>rocks");

   int w, h, r, x, y; // parameters of iris circle

   DemoWindows() {

      // build and diplay the windows
      window1.add(text1);
      window1.pack();
      centerOnScreen(window1);
      window1.setVisible(true);

      window2.setUndecorated(true);
      setTransparent(window2);
      setAlpha(window2, 0.0f);

      text2.setFont(new Font("Arial", 1, 60));
      text2.setForeground(Color.red);

      window2.add(text2);
      window2.pack();
      centerOnScreen(window2);
      window2.setVisible(true);

      // parameters of the smallest circle that encloses window2
      // this is the starting pouint for the "iris out" effect
      w = window2.getWidth();
      h = window2.getHeight();
      r = (int) Math.sqrt(w * w + h * h) / 2; // radius
      x = w / 2 - r; // top left coordinates of circle
      y = h / 2 - r;

   }

   @Override
   public void actionPerformed(ActionEvent e) {
      // called by timer 20 times per sec
      // goes thru a number of phases, each a few seconds long
      switch (phase) {
      case 0: {
         // initial pause
         if (++count > 50) {
            phase = 1; // go to next phase
            count = 0;
         }
         break;
      }
      case 1: {
         // fade in
         if (++count < 100) {
            setAlpha(window2, 0.01f * count);
         } else {
            phase = 2; // go to next phase
            count = 0;
         }
         break;
      }
      case 2: {
         // move
         if (++count < 160) {
            if (count < 28 || count > 80) // pause for best effect
               window2.setLocation(window2.getX() + 1, window2.getY() + 1);
         } else {
            phase = 3; // go to next phase
            count = 0;
         }
         break;
      }
      case 3: {
         // iris out
         if (++count < r) {
            Shape shape = new Ellipse2D.Double(x + count, y + count, 2 * (r - count),
                  2 * (r - count));
            setShape(window2, shape);
         } else {
            phase = 99; // go to final (exit) phase
         }
         break;
      }
      case 99:
         System.exit(0);
      }

   }

   void centerOnScreen(JFrame window) { // convenience method
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation((screenSize.width - window.getWidth()) / 2,
            (screenSize.height - window.getHeight()) / 2);
   }

   // here's the magic:

   private boolean usingAwtUtilities = true;
   private Class<?> awtUtilitiesClass = null;
   private Method mSetWindowOpaque, mSetWindowOpacity, mSetWindowShape;

   void initReflection() {
      if (System.getProperty("java.version").startsWith("1.6")) {
         // Sun doc recommends accessing awtUtilities stuff via Reflection
         // (presumably to avoid access restriction rules)
         try {
            awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
            mSetWindowOpaque = awtUtilitiesClass.getMethod("setWindowOpaque",
                  Window.class, boolean.class);
            mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity",
                  Window.class, float.class);
            mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class,
                  Shape.class);
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else { // no need to do anything for 1.7 and later
         usingAwtUtilities = false;
      }
   }

   void setTransparent(JFrame window) {
      // cover for temporary API expected to change for Java 7
      if (usingAwtUtilities && awtUtilitiesClass == null) initReflection();
      if (usingAwtUtilities) {
         try {
            mSetWindowOpaque.invoke(null, window, Boolean.valueOf(false));
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else {
         window.setBackground(new Color(0, 0, 0, 0));
         // Under 1.7 using an alpha <1 sets opaque to false
      }
      window.getRootPane().setOpaque(false);
   }

   void setAlpha(JFrame window, float alpha) {
      // cover for temporary API expected to change for Java 7
      if (usingAwtUtilities && awtUtilitiesClass == null) initReflection();
      if (usingAwtUtilities) {
         try {
            mSetWindowOpacity.invoke(null, window, Float.valueOf(alpha));
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else {  
         // window.setOpacity(alpha);  // needs Java 1.7 to compile
      }
   }

   void setShape(JFrame window, Shape shape) {
      // cover for temporary API expected to change for Java 7
      if (usingAwtUtilities && awtUtilitiesClass == null) initReflection();
      if (usingAwtUtilities) {
         try {
            mSetWindowShape.invoke(null, window, shape);
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else {
         // window.setShape(shape);   // needs Java 1.7 to compile
      }
   }

}

ps:Also works brilliantly with transparent gifs/pngs - just stick them in a JLabel as an ImageIcon

pps: I notice your code has a convolution filter, so if you also want to do blurring or whatever, "proper" transparency also works beautifully with an overridden paint(...) method - the alpha values are used just like you'd hope.

ppps: I don't know DrJava, but I can very strongly recommend Eclipse. NewBeans also seems to be a popular choice. Eclipse and NetBeans seem to be the only Java IDEs in really wide use for full-scale commercial development.
(Unlike Norm I would never think of trying to work with source code without a good IDE to do most of the donkey work for me.)

ppps: I don't know DrJava, but I can very strongly recommend Eclipse. NewBeans also seems to be a popular choice. Eclipse and NetBeans seem to be the only Java IDEs in really wide use for full-scale commercial development.
(Unlike Norm I would never think of trying to work with source code without a good IDE to do most of the donkey work for me.)

I am running Java 1.6.0 update 21 and so when I checked out the Eclipse Web site Download page and found the following message:
Attention Windows users running Java 1.6.0 update 21 with Eclipse. Please follow the instructions here to resolve crashing and freezing issues.

I have to be honest... This does not exactly inspire confidence in the product. Perhaps I will wait a bit.

That was a Java bug, but whatever.

Once again, I found some code that seems to be doing something that I would like to try, but I get a Static Error when I try to run the code (apparently, I may be the only one).

By the way, the code comes from the book, "Swing Hacks" By Joshua Marinacci, Chris Adamson. Credit where credit is due.

Here is the run-time error message:
Static Error: No constructor in TransparentBackground matches this invocation
Arguments: ()
Candidate signatures: TransparentBackground(JFrame)

And here is the code I am compiling and running in DrJava:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
 
 
 
public class TransparentBackground extends JComponent
  implements ComponentListener, WindowFocusListener, Runnable {
 
 // constants ---------------------------------------------------------------
 // instance ----------------------------------------------------------------
 private JFrame _frame;
 private BufferedImage _background;
 private long _lastUpdate = 0;
 private boolean _refreshRequested = true;
 private Robot _robot;
 private Rectangle _screenRect;
 private ConvolveOp _blurOp;
 
 // constructor -------------------------------------------------------------
 
 public TransparentBackground(JFrame frame) {
  _frame = frame;
  try {
   _robot = new Robot();
  } catch (AWTException e) {
   e.printStackTrace();
   return;
  }
 
  Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
  _screenRect = new Rectangle(dim.width, dim.height);
 
  float[] my_kernel = {
    0.10f, 0.10f, 0.10f,
    0.10f, 0.20f, 0.10f,
    0.10f, 0.10f, 0.10f};
  _blurOp = new ConvolveOp(new Kernel(3, 3, my_kernel));
 
  updateBackground();
  _frame.addComponentListener(this);
  _frame.addWindowFocusListener(this);
  new Thread(this).start();
 }
 
 // protected ---------------------------------------------------------------
 
 protected void updateBackground() {
  _background = _robot.createScreenCapture(_screenRect);
 }
 
 
 
 protected void refresh() {
  if (_frame.isVisible() && this.isVisible()) {
   repaint();
   _refreshRequested = true;
   _lastUpdate = System.currentTimeMillis();
  }
 }
 
 
 // JComponent --------------------------------------------------------------
 
 protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
  Point pos = this.getLocationOnScreen();
  BufferedImage buf = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
  buf.getGraphics().drawImage(_background, -pos.x, -pos.y, null);
 
  Image img = _blurOp.filter(buf, null);
  g2.drawImage(img, 0, 0, null);
  g2.setColor(new Color(255, 255, 255, 192));
  g2.fillRect(0, 0, getWidth(), getHeight());
 }
 
 // ComponentListener -------------------------------------------------------
 public void componentHidden(ComponentEvent e) {
 }
 
 public void componentMoved(ComponentEvent e) {
  repaint();
 }
 
 public void componentResized(ComponentEvent e) {
  repaint();
 
 }
 
 public void componentShown(ComponentEvent e) {
  repaint();
 }
 
 // WindowFocusListener -----------------------------------------------------
 public void windowGainedFocus(WindowEvent e) {
  refresh();
 }
 
 public void windowLostFocus(WindowEvent e) {
  refresh();
 }
 
 // Runnable ----------------------------------------------------------------
 public void run() {
  try {
   while (true) {
    Thread.sleep(100);
    long now = System.currentTimeMillis();
    if (_refreshRequested && ((now - _lastUpdate) > 1000)) {
     if (_frame.isVisible()) {
      Point location = _frame.getLocation();
      _frame.setLocation(-_frame.getWidth(), -_frame.getHeight());
      updateBackground();
      _frame.setLocation(location);
      refresh();
     }
     _lastUpdate = now;
     _refreshRequested = false;
    }
   }
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  JFrame frame = new JFrame("Transparent Window");
  TransparentBackground bg = new TransparentBackground(frame);
 
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(bg);
  frame.pack();
  frame.setSize(200, 200);
  frame.setLocation(500, 500);
  frame.setVisible(true);
 }
}

Apparently, I have found a bug in the DrJava IDE. So, if you use DrJava, here is a workaround, until the developers at SourceForge work on a fix...

Instead of using the "Run" command button, type the following phrase into the interactions pane:

TransparentBackground.main(new String[0]);

In addition, you can also turn off the "smart run" feature:
Go to Edit, Preferences, and then select the Interactions Pane category in the Preferences window. There, remove the check mark from "Smart Run".

Thanks to everyone that responded. I will try to update this thread when they have a fix for bug.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.