tranparent jframe with resize option

tranparent jframe with resize option

Page 1 of 1

4 Replies - 2487 Views - Last Post: 20 January 2010 - 08:26 PM Rate Topic: -----

#1 arunjassiar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-May 09

tranparent jframe with resize option

Posted 20 January 2010 - 12:34 AM

I want to have transparent frame or panel with border which can be re-sized also.
basically i want to highlight the screen area on desktop so that particular area being be captured .

any one can reply me on if we can do some thing like in java , just check out following
http://www.screentoaster.com/ click on ?start recording?.
http://screenr.com/ click on ?Record your screen cast now?
http://www.screencast-o-matic.com/ click on ?Create? button.
, basically i want transparent frame or any thing with border and re-sizable.

This post has been edited by arunjassiar: 20 January 2010 - 12:38 AM


Is This A Good Question/Topic? 0
  • +

Replies To: tranparent jframe with resize option

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8017
  • View blog
  • Posts: 31,125
  • Joined: 06-March 08

Re: tranparent jframe with resize option

Posted 20 January 2010 - 06:02 PM

Written years ago but it might do the job... I mean I would probably rewrite it better today

package ca.pblinc.capture;

// Capture.java

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

import javax.imageio.*;
import javax.imageio.stream.*;
import javax.swing.*;

/**
 *  This class defines the application GUI and starts the application.
 */

public class Capture extends JFrame
{
   /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	*  Width and height of screen. A single screen is assumed.
	*/

   Dimension dimScreenSize;

   /**
	*  Component for presenting captured image.
	*/

   ImageArea ia = new ImageArea ();

   /**
	*  Screen width and height as a Rectangle. This is a convenience for
	*  Robot's createScreenCapture() method.
	*/

   Rectangle rectScreenSize;

   /**
	*  Robot is needed to capture screen contents.
	*/

   static Robot robot;

   /**
	*  To support the display of images that can't be fully displayed without
	*  scrolling, the ImageArea component is placed into a JScrollPane.
	*/

   JScrollPane jsp;
   
   BufferedImage oldB;

   /**
	*  Construct a Capture GUI.
	*
	*  @param title text appearing in the title bar of Capture's main window
	*/

   public Capture (String title)
   {
	  // Place title in the title bar of Capture's main window.

	  super (title);

	  // Exit the application if user selects Close from system menu.

	  setDefaultCloseOperation (EXIT_ON_CLOSE);

	  // Save screen dimensions for initially positioning main window and
	  // performing screen captures.

	  dimScreenSize = Toolkit.getDefaultToolkit ().getScreenSize ();

	  // Copy screen dimensions to Rectangle for use with Robot's
	  // createScreenCapture() method.

	  rectScreenSize = new Rectangle (dimScreenSize);

	  // Construct a save file chooser. Initialize the starting directory to
	  // the current directory, do not allow the user to select the "all files"
	  // filter, and restrict the files that can be selected to those ending
	  // with .jpg or .jpeg extensions.

	  final JFileChooser fcSave = new JFileChooser ();
	  fcSave.setCurrentDirectory (new File (System.getProperty ("user.dir")));
	  fcSave.setAcceptAllFileFilterUsed (false);
	  fcSave.setFileFilter (new ImageFileFilter ());

	  // Create the application's menus.

	  JMenuBar mb = new JMenuBar ();

	  JMenu menu = new JMenu ("File");

	  ActionListener al;

	  JMenuItem mi = new JMenuItem ("Save As...");
	  mi.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_S,
												 InputEvent.ALT_MASK));
	  al = new ActionListener ()
		   {
			   public void actionPerformed (ActionEvent e)
			   {
				  // Disallow image saving if there is no image to save.

				  if (ia.getImage () == null)
				  {
					  showError ("No captured image.");
					  return;
				  }

				  // Present the "save" file chooser without any file selected.
				  // If the user cancels this file chooser, exit this method.

				  fcSave.setSelectedFile (null);
				  if (fcSave.showSaveDialog (Capture.this) !=
					  JFileChooser.APPROVE_OPTION)
					  return;

				  // Obtain the selected file. Validate its extension, which 
				  // must be .jpg or .jpeg. If extension not present, append
				  // .jpg extension.

				  File file = fcSave.getSelectedFile ();
				  String path = file.getAbsolutePath ().toLowerCase ();
				  if (!path.endsWith (".jpg") && !path.endsWith (".jpeg"))
					  file = new File (path += ".jpg");

				  // If the file exists, inform the user, who might not want
				  // to accidentally overwrite an existing file. Exit method
				  // if the user specifies that it is not okay to overwrite
				  // the file.
				  
				  if (file.exists ())
				  {
					  int choice =  JOptionPane.
									showConfirmDialog (null,
													   "Overwrite file?",
													   "Capture",
													   JOptionPane.
													   YES_NO_OPTION);
					  if (choice == JOptionPane.NO_OPTION)
						  return;
				  }

				  // If the file does not exist or the user gives permission,
				  // save image to file.

				  ImageWriter writer = null;
				  ImageOutputStream ios = null;

				  try
				  {
					  // Obtain a writer based on the jpeg format.

					  Iterator iter;
					  iter = ImageIO.getImageWritersByFormatName ("jpeg");

					  // Validate existence of writer.

					  if (!iter.hasNext ())
					  {
						  showError ("Unable to save image to jpeg file type.");
						  return;
					  }

					  // Extract writer.

					  writer = (ImageWriter) iter.next();

					  // Configure writer output destination.

					  ios = ImageIO.createImageOutputStream (file);
					  writer.setOutput (ios);

					  // Set JPEG compression quality to 95%.

					  ImageWriteParam iwp = writer.getDefaultWriteParam ();
					  iwp.setCompressionMode (ImageWriteParam.MODE_EXPLICIT);
					  iwp.setCompressionQuality (0.95f);

					  // Write the image.

					  writer.write (null,
									new IIOImage ((BufferedImage)
												  ia.getImage (), null, null),
									iwp);
				  }
				  catch (IOException e2)
				  {
					  showError (e2.getMessage ());
				  }
				  finally
				  {
					  try
					  {
						  // Cleanup.

						  if (ios != null)
						  {
							  ios.flush ();
							  ios.close ();
						  }

						  if (writer != null)
							  writer.dispose ();
					  }
					  catch (IOException e2)
					  {
					  }
				  }
			   }
		   };

	  mi.addActionListener (al);
	  menu.add (mi);

	  menu.addSeparator ();

	  mi = new JMenuItem ("Exit");
	  mi.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_X,
												 InputEvent.ALT_MASK));
	  mi.addActionListener (new ActionListener ()
							{
								public void actionPerformed (ActionEvent e)
								{
								   System.exit (0);
								}
							});
	  menu.add (mi);

	  mb.add (menu);

	  menu = new JMenu ("Capture");

	  mi = new JMenuItem ("Capture");
	  mi.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_C,
												 InputEvent.ALT_MASK));
	  al = new ActionListener ()
		   {
			   public void actionPerformed (ActionEvent e)
			   {
				  // Hide Capture's main window so that it does not appear in
				  // the screen capture.

				  setVisible (false);

				  // Perform the screen capture...

				  BufferedImage biScreen;
				  biScreen = robot.createScreenCapture (rectScreenSize);
				  if(oldB != null) {
					  boolean dif = false;
					  for(int i = 0; i < oldB.getWidth(); i++) {
						  for(int j = 0; j < oldB.getHeight(); j++) {
							  if(oldB.getRGB(i, j) != biScreen.getRGB(i, j)) {
								  System.out.println("Le pixel " + i + "," + j + " est different");
 //			   				  dif = true;
								  break;
							  }
						  }
						  if(dif)
							  break;
					  }
					  if(!dif) System.out.println("Les images sont pareilles");
				  }
				  oldB = biScreen;

				  // Show Capture's main window for continued user interaction.

				  setVisible (true);

				  // Update ImageArea component with the new image, and adjust
				  // the scrollbars.

				  ia.setImage (biScreen);

				  jsp.getHorizontalScrollBar ().setValue (0);
				  jsp.getVerticalScrollBar ().setValue (0);
			   }
		   };

	  mi.addActionListener (al);
	  menu.add (mi);

	  mb.add (menu);

	  mi = new JMenuItem ("Crop");
	  mi.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_K,
												 InputEvent.ALT_MASK));
	  al = new ActionListener ()
		   {
			   public void actionPerformed (ActionEvent e)
			   {
				  // Crop ImageArea component and adjust the scrollbars if
				  // cropping succeeds.

				  if (ia.crop ())
				  {
					  jsp.getHorizontalScrollBar ().setValue (0);
					  jsp.getVerticalScrollBar ().setValue (0);
				  }
				  else
					  showError ("Out of bounds.");
			   }
		   };

	  mi.addActionListener (al);
	  menu.add (mi);

	  mb.add (menu);

	  // Install these menus.

	  setJMenuBar (mb);

	  // Install a scollable ImageArea component.

	  getContentPane ().add (jsp = new JScrollPane (ia));

	  // Size main window to half the screen's size, and center window.

	  setSize (dimScreenSize.width/2, dimScreenSize.height/2);

	  setLocation ((dimScreenSize.width-dimScreenSize.width/2)/2,
				   (dimScreenSize.height-dimScreenSize.height/2)/2);

	  // Display the GUI and start the event-handling thread.

	  setVisible (true);
   }

   /**
	*  Present an error message via a dialog box.
	*
	*  @param message the message to be presented
	*/

   public static void showError (String message)
   {
	  JOptionPane.showMessageDialog (null, message, "Capture",
									 JOptionPane.ERROR_MESSAGE);
   }

   /**
	*  Application entry point.
	*
	*  @param args array of command-line arguments
	*/

   public static void main (String [] args)
   {
	  try
	  {
		  robot = new Robot ();
	  }
	  catch (AWTException e)
	  {
		  showError (e.getMessage ());
		  System.exit (0);
	  }
	  catch (SecurityException e)
	  {
		  showError ("Permission required to use Robot.");
		  System.exit (0);
	  }

	  // Construct the GUI and begin the event-handling thread.

	  new Capture ("Capture");
   }
}


package ca.pblinc.capture;

// ImageArea.java

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

import javax.swing.*;

/**
 *  This class defines a specialized panel for displaying a captured image.
 */

public class ImageArea extends JPanel
{
   /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

/**
	*  Stroke-defined outline of selection rectangle.
	*/

   private BasicStroke bs;

   /**
	*  A gradient paint is used to create a distinctive-looking selection
	*  rectangle outline.
	*/

   private GradientPaint gp;

   /**
	*  Displayed image's Image object, which is actually a BufferedImage.
	*/

   private Image image;

   /**
	*  Mouse coordinates when mouse button pressed.
	*/

   private int srcx, srcy;

   /**
	*  Latest mouse coordinates during drag operation.
	*/

   private int destx, desty;

   /**
	*  Location and extents of selection rectangle.
	*/

   private Rectangle rectSelection;

   /**
	*  Construct an ImageArea component.
	*/

   public ImageArea ()
   {
	  // Create a selection Rectangle. It's better to create one Rectangle
	  // here than a Rectangle each time paintComponent() is called, to reduce
	  // unnecessary object creation.

	  rectSelection = new Rectangle ();

	  // Define the stroke for drawing selection rectangle outline.

	  bs = new BasicStroke (5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
							0, new float [] { 12, 12 }, 0);

	  // Define the gradient paint for coloring selection rectangle outline.

	  gp = new GradientPaint (0.0f, 0.0f, Color.red, 1.0f, 1.0f, Color.white,
							  true);

	  // Install a mouse listener that sets things up for a selection drag.

	  MouseListener ml;
	  ml = new MouseAdapter ()
		   {
			   public void mousePressed (MouseEvent e)
			   {
				  // When you start Capture, there is no captured image.
				  // Therefore, it makes no sense to try and select a subimage.
				  // This is the reason for the if (image == null) test.

				  if (image == null)
					  return;

				  destx = srcx = e.getX ();
				  desty = srcy = e.getY ();

				  repaint ();
			   }
		   };
	  addMouseListener (ml);

	  // Install a mouse motion listener to update the selection rectangle
	  // during drag operations.

	  MouseMotionListener mml;
	  mml = new MouseMotionAdapter ()
			{
				public void mouseDragged (MouseEvent e)
				{
				   // When you start Capture, there is no captured image.
				   // Therefore, it makes no sense to try and select a
				   // subimage. This is the reason for the if (image == null)
				   // test.

				   if (image == null)
					   return;

				   destx = e.getX ();
				   desty = e.getY ();

				   repaint (); 
				}
			};
	  addMouseMotionListener (mml);
   }

   /**
	*  Crop the image to the dimensions of the selection rectangle.
	*
	*  @return true if cropping succeeded
	*/

   public boolean crop ()
   {
	  // There is nothing to crop if the selection rectangle is only a single
	  // point.

	  if (srcx == destx && srcy == desty)
		  return true;

	  // Assume success.

	  boolean succeeded = true;

	  // Compute upper-left and lower-right coordinates for selection rectangle
	  // corners.

	  int x1 = (srcx < destx) ? srcx : destx;
	  int y1 = (srcy < desty) ? srcy : desty;

	  int x2 = (srcx > destx) ? srcx : destx;
	  int y2 = (srcy > desty) ? srcy : desty;

	  // Compute width and height of selection rectangle.

	  int width = (x2-x1)+1;
	  int height = (y2-y1)+1;

	  // Create a buffer to hold cropped image.

	  BufferedImage biCrop = new BufferedImage (width, height,
												BufferedImage.TYPE_INT_RGB);
	  Graphics2D g2d = biCrop.createGraphics ();

	  // Perform the crop operation.

	  try
	  {
		  BufferedImage bi = (BufferedImage) image;
		  BufferedImage bi2 = bi.getSubimage (x1, y1, width, height);
		  g2d.drawImage (bi2, null, 0, 0);
	  }
	  catch (RasterFormatException e)
	  {
		 succeeded = false;
	  }

	  g2d.dispose ();

	  if (succeeded)
		  setImage (biCrop); // Implicitly remove selection rectangle.
	  else
	  {
		  // Prepare to remove selection rectangle.

		  srcx = destx;
		  srcy = desty;

		  // Explicitly remove selection rectangle.

		  repaint ();
	  }

	  return succeeded;
   }

   /**
	*  Return the current image.
	*
	*  @return Image reference to current image
	*/

   public Image getImage ()
   {
	  return image;
   }

   /**
	*  Repaint the ImageArea with the current image's pixels.
	*
	*  @param g graphics context
	*/

   public void paintComponent (Graphics g)
   {
	  // Repaint the component's background.

	  super.paintComponent (g);

	  // If an image has been defined, draw that image using the Component
	  // layer of this ImageArea object as the ImageObserver.

	  if (image != null)
		  g.drawImage (image, 0, 0, this);

	  // Draw the selection rectangle if present.

	  if (srcx != destx || srcy != desty)
	  {
		  // Compute upper-left and lower-right coordinates for selection
		  // rectangle corners.

		  int x1 = (srcx < destx) ? srcx : destx;
		  int y1 = (srcy < desty) ? srcy : desty;

		  int x2 = (srcx > destx) ? srcx : destx;
		  int y2 = (srcy > desty) ? srcy : desty;

		  // Establish selection rectangle origin.

		  rectSelection.x = x1;
		  rectSelection.y = y1;

		  // Establish selection rectangle extents.

		  rectSelection.width = (x2-x1)+1;
		  rectSelection.height = (y2-y1)+1;

		  // Draw selection rectangle.

		  Graphics2D g2d = (Graphics2D) g;
		  g2d.setStroke (bs);
		  g2d.setPaint (gp);
		  g2d.draw (rectSelection);
	  }
   }

   /**
	*  Establish a new image and update the display.
	*
	*  @param image new image's Image reference
	*/

   public void setImage (Image image)
   {
	  // Save the image for later repaint.

	  this.image = image;

	  // Set this panel's preferred size to the image's size, to influence the
	  // display of scrollbars.
 
	  setPreferredSize (new Dimension (image.getWidth (this),
									   image.getHeight (this)));

	  // Present scrollbars as necessary.

	  revalidate ();

	  // Prepare to remove any selection rectangle.

	  srcx = destx;
	  srcy = desty;

	  // Update the image displayed on the panel.

	  repaint ();
   }
}


package ca.pblinc.capture;

// ImageFileFilter.java

import java.io.*;

/**
 *  This class defines a filter that accepts directories and files ending in
 *  .jpg or .jpeg extensions.
 */

class ImageFileFilter extends javax.swing.filechooser.FileFilter
{
   /**
	*  Accept all directories and specified files.
	*
	*  @param f file being checked
	*
	*  @return true if accepted
	*/

   public boolean accept (File f)
   {
	  // Allow the user to select directories so that the user can navigate the
	  // file system.

	  if (f.isDirectory ())
		  return true;

	  // Allow the user to select files ending with a .jpg or a .jpeg
	  // extension.

	  String s = f.getName ();
	  int i = s.lastIndexOf ('.');

	  if (i > 0 && i < s.length ()-1)
	  {
		  String ext = s.substring (i+1).toLowerCase ();

		  if (ext.equals ("jpg") || ext.equals ("jpeg"))
			  return true;
	  }

	  // Nothing else can be selected.

	  return false;
   }

   /**
	*  Return a description that appears on the file chooser and tells the user
	*  which files can be selected.
	*
	*  @return description
	*/

   public String getDescription ()
   {
	  return "Accepts .jpg and .jpeg files";
   }
}


Was This Post Helpful? 0
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2695
  • View blog
  • Posts: 10,555
  • Joined: 15-July 08

Re: tranparent jframe with resize option

Posted 20 January 2010 - 07:33 PM

And I actually wrote a Transparent GUI Library as a challenge a few months ago. It has not matured yet, and you have to add components in a special way, but you're free to use it!

Look in post #17 for updated post.
http://www.dreaminco...topic142763.htm
Was This Post Helpful? 0
  • +
  • -

#4 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,828
  • Joined: 02-January 06

Re: tranparent jframe with resize option

Posted 20 January 2010 - 08:18 PM

I played around with "transparent frames" in Swing a few years back but if I were doing that these days I'd choose JavaFX.
http://javafx.com/sa...ndow/index.html
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8017
  • View blog
  • Posts: 31,125
  • Joined: 06-March 08

Re: tranparent jframe with resize option

Posted 20 January 2010 - 08:26 PM

Arunjassiar does not want a transparent frame
he wants to capture a part of its desktop with a rectangular area to select the part of the screen to capture
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1