I have this webcam program that runs in a JFrame. Whenever I close the frame, it prints out "Closed" like it's supposed to, but my IDE says that is still running. Why is this and how do I fix it? I am not running any threads anywhere in the program. This doesn't have anything to do with the default close operation as I have tested for that already.
public class Webcam extends JPanel {
private static BufferedImage image;
public Webcam() {
super();
}
public static void main(String args[]) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
JFrame frame = new JFrame("Webcam");
Webcam panel = new Webcam();
// Initialize JPanel parameters
//frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(1080, 720);
frame.setContentPane(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
System.exit(0);
}
});
Mat currentImage = new Mat();
VideoCapture capture = new VideoCapture(0);
if(capture.isOpened()) {
// Infinitely update the images
while(true) {
// VideoCapture returns current Mat
capture.read(currentImage);
if(!currentImage.empty()) {
frame.setSize(currentImage.width() + 40, currentImage.height() + 60);
image = panel.matrixToBuffer(currentImage);
// Update the panel
panel.repaint();
}
else {
System.out.println("Error: no frame captured");
frame.dispose();
System.exit(0);
break;
}
}
}
return;
}
Okay, while I appreciate all of the helpful comments, the issue was that the VideoCapture had an internal thread running, and adding capture.release() to my listener fixed it.
Very simply, I could not draw this image.
public class RenderMap extends JPanel {
static BufferedImage brick;
static BufferedImage groundb;
public static void main(String[] args) {
JFrame window = new JFrame("Super Mario");
RenderMap content = new RenderMap();
window.setContentPane(content);
window.setBackground(Color.WHITE);
window.setSize(1200, 800);
window.setLocation(100,0);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
try {
brick = ImageIO.read(new File("SuperMario/brick.png"));
} catch (IOException e) {
}
try {
URL url = new URL("SuperMario/brick.png");
brick = ImageIO.read(url);
} catch (IOException e) {
}
try {
groundb = ImageIO.read(new File("SuperMario/ground.png"));
} catch (IOException e) {
}
try {
URL url = new URL("SuperMario/ground.png");
groundb = ImageIO.read(url);
} catch (IOException e) {
}
}
public Ground ground;
public RenderMap() {}
public void paintComponent(Graphics g) {
if(ground == null) {
ground = new Ground();
}
ground.draw(g);
}
public class Ground implements ImageObserver {
Ground(){}
void draw(Graphics g) {
g.drawImage(groundb, 0, 0, 1200, 800, this);
g.fillOval( 8, 8, 16, 16);
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
// TODO Auto-generated method stub
return false;
}
}
}
This draws the oval, but not the image. I tried changing to another image(that is functioning in another program) and it still won't work, so I know it's not the image's problem.
As suspected, the images are not being loaded properly.
java.net.MalformedURLException: no protocol: SuperMario/brick.png
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at RenderMap.main(RenderMap.java:40)
java.net.MalformedURLException: no protocol: SuperMario/ground.png
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at RenderMap.main(RenderMap.java:51)
It's failing at the load-by-URL function calls because you passed in an invalid URL. Correct URL format should be like how you access them from a web browser, like: http://someplace.com/SuperMarioFolder/brick.png
To load the images, choose only one way to read them. Either by:
URL - Remove the File blocks and make the file accessible via full URL.
try {
URL url = new URL("http://www.proper-url.com/SuperMario/ground.png");
groundb = ImageIO.read(url);
} catch (IOException e) { }
File - Remove the URL blocks. This will only allow the program to access local files.
try {
groundb = ImageIO.read(new File("SuperMario/ground.png"));
} catch (IOException e) {
}
For your project's purpose, I believe option#2 would suffice.
Moving forward, you may want to use an IDE's debugging feature to go through code execution step-by-step. If you're not using one, you may want to IntelliJ and Eclipse.
[enter link description here][1]I tried an application to display a GIF file. But my application is not showing any error instead GIf ( splash screen ) is not visible.
I have given a code in manifest file :
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build SplashScreen-Image:C:\Users\Admin\Documents\NetBeansProjects\splash\src\splash\try5.gif
-splash:src\splash\try5.gif
the above code in VM options.
In my main class i used this code
public static void main(String[] args) {
sleepThread();
java.awt.EventQueue.invokeLater(new Runnable(){
#Override
public void run()
{
new welcome().setVisible(true);
}
});
}
private static void sleepThread() {
try
{
Thread.sleep(5000);
}
catch (InterruptedException ex)
{
// Do something, if there is a exception
System.out.println(ex.toString());
}
}
// TODO code application logic here
}
But when i tried running my application it doesnot display my Splashscreen. Is there any specification for the size of the Splashscreen GIf because my file is 2.63 MB and its dimensions are 640 * 360. Kindly help me.
EDIT : I USED THE SAME CODING BUT TRIED A JPG IMAGE AS A SPLASH SCREEN IT WORKED WELL. THEN AGAIN I CHANGED IT TO .GIF FILE THE SPLASH SCREEN DID NOT APPEAR AND ALSO AGAIN I CHANGED MY FILE WITH JPG FILE THIS TIME THIS JPG FILE ALSO DID NOT WORK.
EDIT : [1]: http://giphy.com/gifs/thank-you-cute-a3IWyhkEC0p32
Here is the link i have given for a sample gif file. But please note that my gif file size is 2.53 MB.
EDIT : Now this Gif file works perfectly. But after dis splash screen stops my Jframe should open. how do i map it so dat it if i run my program it First displays my Splashscreen den my Frame.
Oops!
I didn't notice. It is better to use SwingUtilities for forms and swing objects to work with. // Change the sleep to 5000, it is 2000 now.
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class test {
public static void main(String[] args) {
final JDialog frame = new JDialog(new JFrame());
frame.setSize(320, 240);
frame.setContentPane(new JLabel(new ImageIcon("H:\\walk.gif")));
frame.setUndecorated(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
new Thread(new Runnable() {
#Override
public void run() {
sleepThread();
CloseDialog(frame);
System.exit(0);
}
}).start();
ShowDialog(frame);
}
private static void sleepThread() {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
// Do something, if there is a exception
System.out.println(ex.toString());
}
}
private static void ShowDialog(final JDialog dialog) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
private static void CloseDialog(final JDialog dialog) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(false);
}
});
}
}
swap commands, and you will be fine. Show the window, then sleep. That is how splash screen work, I think :)
public static void main(String[] args) {
new welcome().setVisible(true);
java.awt.EventQueue.invokeLater(new Runnable(){
#Override
public void run()
{
sleepThread();
}
});
}
private static void sleepThread() {
try
{
Thread.sleep(5000);
}
catch (InterruptedException ex)
{
// Do something, if there is a exception
System.out.println(ex.toString());
}
}
// TODO code application logic here
}
I have a Java Applet (java.applet.Applet) embedded into an HTML page. There is a Control class, which extends Applet and a Panel (java.awt.Panel) the same shape and size of the Applet which displays everything on the screen.
When I run the project from the NetBeans IDE, everything displays as intended: the Applet opens and contains a Panel with my splash screen.
When I run the project from the HTML page on my website, I see a blank white page. The images do load; in Google Chrome, I can right-click the page and click "Inspect Element", and the whole game displays and functions properly. You can view the page at http://www.philipthegreat.com/control.html.
My thought: the Panel is displaying behind the Applet instead of in front of the Applet.
Here is the code in the Control and SplashScreen classes.
Control
public class Control extends Applet {
private Panel displayPanel;
#Override
public void init() {
setFocusable(true);
}
#Override
public void start() {
displayPanel = new SplashScreen(this);
add(displayPanel);
displayPanel.requestFocus();
}
public void setDisplayPanel (Panel displayPanel) {
remove(this.displayPanel);
this.displayPanel = displayPanel;
add(this.displayPanel);
this.displayPanel.requestFocus();
}
}
SplashScreen
public SplashScreen(Control control) {
setLayout(null);
setSize(800,600);
setBackground(Color.BLUE);
this.control = control;
init();
}
public void init() {
try {
splashScreen = ImageIO.read(getClass().getResourceAsStream("/images/SplashScreen.png"));
} catch (Exception e) {
e.printStackTrace();
}
addMouseListener((MouseListener) this);
}
public void destroy() {
}
#Override
public void paint(Graphics g) {
g.drawImage(splashScreen, 0, 0, null);
}
As I am relatively new to Java, any pointers would be appreciated.
Try this as Control.java instead of your Control.java
//<applet code="Control.java" height=200 width=500></applet>
public class Control extends JApplet {
private Panel displayPanel;
#Override
public void init() {
setFocusable(true);
}
#Override
public void start() {
displayPanel = new SplashScreen(this);
add(displayPanel);
displayPanel.requestFocus();
}
public void setDisplayPanel(Panel displayPanel) {
remove(this.displayPanel);
this.displayPanel = displayPanel;
add(this.displayPanel);
this.displayPanel.requestFocus();
}
}
I am trying to create a circle-shaped window that follows the mouse and pass clicks to the underlying windows.
I was doing this with Python and Qt (see Python overlay window) but then I switched to Java and Swing. However I'm not able to make the window transparent. I tried this method but it doesn't work, however I think that my system supports the transparency because if I start Screencast-O-Matic (which is in Java), the rectangle is actually transparent.
How can I achieve something like that? (I'm on Linux KDE4)
Why did the Java tutorial How to Create Translucent and Shaped Windows fail to work? Are you using the latest version of Java 6 or Java 7?
In the May/June issue of Java Magazine, there was a tutorial on shaped and transparent windows requiring java 7. You will probably need to sign up for Java magazine in order to read it. See if you can get this to run on your system:
import java.awt.*; //Graphics2D, LinearGradientPaint, Point, Window, Window.Type;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* From JavaMagazine May/June 2012
* #author josh
*/
public class ShapedAboutWindowDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//switch to the right thread
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("About box");
//turn of window decorations
frame.setUndecorated(true);
//turn off the background
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new AboutComponent());
frame.pack();
//size the window
frame.setSize(500, 200);
frame.setVisible(true);
//center on screen
frame.setLocationRelativeTo(null);
}
}
);
}
private static class AboutComponent extends JComponent {
public void paintComponent(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
//create a translucent gradient
Color[] colors = new Color[]{
new Color(0,0,0,0)
,new Color(0.3f,0.3f,0.3f,1f)
,new Color(0.3f,0.3f,0.3f,1f)
,new Color(0,0,0,0)};
float[] stops = new float[]{0,0.2f,0.8f,1f};
LinearGradientPaint paint = new LinearGradientPaint(
new Point(0,0), new Point(500,0),
stops,colors);
//fill a rect then paint with text
g.setPaint(paint);
g.fillRect(0, 0, 500, 200);
g.setPaint(Color.WHITE);
g.drawString("My Killer App", 200, 100);
}
}
}
If you're using Java 6, you need to make use of the private API AWTUtilities. Check out the Java SE 6 Update 10 API for more details
EXAMPLE
This is a bit of quick hack, but it gets the idea across
public class TransparentWindow {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.setUndecorated(true);
String version = System.getProperty("java.version");
if (version.startsWith("1.7")) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice graphicsDevice = ge.getDefaultScreenDevice();
System.out.println("Transparent from under Java 7");
/* This won't run under Java 6, uncomment if you are using Java 7
System.out.println("isPerPixelAlphaTranslucent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT));
System.out.println("isPerPixelAlphaTransparent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT));
System.out.println("isPerPixelAlphaTranslucent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT));
*/
frame.setBackground(new Color(0, 0, 0, 0));
} else if (version.startsWith("1.6")) {
System.out.println("Transparent from under Java 6");
System.out.println("isPerPixelAlphaSupported = " + supportsPerAlphaPixel());
setOpaque(frame, false);
}
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class MyFrame extends JFrame {
public MyFrame() throws HeadlessException {
setContentPane(new MyContentPane());
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
dispose();
}
}
});
}
}
public static class MyContentPane extends JPanel {
public MyContentPane() {
setLayout(new GridBagLayout());
add(new JLabel("Hello, I'm a transparent frame under Java " + System.getProperty("java.version")));
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLUE);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 20, 20);
}
}
public static boolean supportsPerAlphaPixel() {
boolean support = false;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
return support;
}
public static void setOpaque(Window window, boolean opaque) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
// com.sun.awt.AWTUtilities.setWindowOpaque(this, opaque);
// ((JComponent) window.getContentPane()).setOpaque(opaque);
}
} catch (Exception exp) {
}
}
public static void setOpacity(Window window, float opacity) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpacity", Window.class, float.class);
method.invoke(null, window, opacity);
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static float getOpacity(Window window) {
float opacity = 1f;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("getWindowOpacity", Window.class);
Object value = method.invoke(null, window);
if (value != null && value instanceof Float) {
opacity = ((Float) value).floatValue();
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
return opacity;
}
}
On Windows 7 it produces
Under Java 6
Under Java 7
i guess this will work,i already tried it..to make a JFrame or a window transparent you need to undecorate Undecorated(true) the frame first. Here is sample code :
import javax.swing.*;
import com.sun.awt.AWTUtilities;
import java.awt.Color;
class transFrame {
private JFrame f=new JFrame();
private JLabel msg=new JLabel("Hello I'm a Transparent Window");
transFrame() {
f.setBounds(400,150,500,500);
f.setLayout(null);
f.setUndecorated(true); // Undecorates the Window
f.setBackground(new Color(0,0,0,25)); // fourth index decides the opacity
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
msg.setBounds(150,250,300,25);
f.add(msg);
f.setVisible(true);
}
public static void main(String[] args) {
new transFrame();
}
}
The only problem is you need to add your own code for close and minimize using buttons.
If you want to do it on your own, without using a external lib, you could start a thread that performs :
set the transparent window invisible
make a Screenshot of the desktop
put this screenshot as background image of your window
Or you could use JavaFX
I was also facing the same problem. After hours of searching, I finally found the problem! These are the lines you must write, if you want to make a transparent JFrame:
public void enableTransparentWindow(float opacity) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
f.setLocationRelativeTo(null);
f.setBackground(new Color(0, 0, 0));
//If translucent windows aren't supported, exit.
f.setUndecorated(true);
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println(
"Translucency is not supported");
System.exit(0);
}
f.setOpacity(opacity);
}
Don't forget to call the setVisible() method after this code.
Happy Coding!