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!
Related
I want to set custom cursor in my java swing app, and then edit it.
I set a custom cusrsor after showing window (in "Window" class).
Later in code (in the other class), I want to chainge it again, so i call this updateCursor() funcion (in "Window" class again), and it and it won't work. There is no errors or warnings, but the cursor isn't changing - just stays the same. I tried, and I can't find answer anywhere. I appreciate any help.
This is full code - Window.java:
import MainMenu;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
public class Window {
public static final int WIDTH = 817, HEIGHT = 640;
JFrame frame = new JFrame("");
public void open() {
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(WIDTH - 33, HEIGHT - 25);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setFocusable(true);
frame.requestFocus();
frame.setFocusTraversalKeysEnabled(true);
frame.addKeyListener(new InputManager());
frame.addMouseListener(new InputManager());
frame.add(new MainMenu());
frame.add(new Game());
loadCursors();
updateCursor(0);
}
public static final int NORMAL = 0, ACTIVE = 1, INACTIVE = 2;
Cursor cursor_normal, cursor_active, cursor_inactive;
public void loadCursors() {
try {
cursor_normal = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_normal)), new Point(0, 0), "custom cursor (normal)");
cursor_active = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_active)), new Point(0, 0), "custom cursor (active)");
cursor_inactive = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_inactive)), new Point(0, 0), "custom cursor (inactive)");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void updateCursor(int cursorType) {
switch (cursorType) {
case NORMAL -> frame.setCursor(cursor_normal);
case ACTIVE -> frame.setCursor(cursor_active);
case INACTIVE -> frame.setCursor(cursor_inactive);
}
}
}
MainMenu.java:
import Window;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MainMenu extends JPanel implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
// testing
new Window().updateCursor(Window.ACTIVE);
}
#Override
public void keyReleased(KeyEvent e) {
}
}
You can't do ...
new Window().updateCursor(Window.ACTIVE);
and magically expect the other instance of Window to be updated, in fact, you don't need to do this at all.
This is going to create another instance/copy of Window, which is not present on the screen and it will have no effect on the instance which is been displayed.
You could call setCursor directly on the instance MainMenu.
Now, if you want to "centralise" the functionality, I would start by creating a "manager" class, for example...
public class CursorManager {
public enum CusorType {
NORMAL, ACTIVE, INACTIVE;
}
private Cursor cursorNormal, cursorActive, cursorInactive;
public CursorManager() throws IOException {
cursorNormal = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_normal)), new Point(0, 0), "custom cursor (normal)");
cursorActive = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_active)), new Point(0, 0), "custom cursor (active)");
cursorInactive = Toolkit.getDefaultToolkit().createCustomCursor(ImageIO.read(new File(new SpritesManager().cursor_inactive)), new Point(0, 0), "custom cursor (inactive)");
}
public void setCursor(CusorType cursorType, Component comp) {
switch (cursorType) {
case NORMAL ->
comp.setCursor(cursorNormal);
case ACTIVE ->
comp.setCursor(cursorActive);
case INACTIVE ->
comp.setCursor(cursorInactive);
}
}
}
I would then create this instance of the manager during the initialisation phase of your code
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
CursorManager cursorManager = new CursorManager();
//.. Every thing else...
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
And then pass this instance to every class that might need it...
// You'll need to update Window to accept this parameter
new Window(cursorManager).open();
And...
public class MainMenu extends JPanel implements KeyListener {
private CursorManager cursorManager;
private MainMenu(CursorManager cursorManager) {
this.cursorManager = cursorManager;
}
#Override
public void keyPressed(KeyEvent e) {
// testing
cursorManager.setCursor(CursorManager.CusorType.ACTIVE, this);
}
//...
}
This is commonly known as "dependency injection" and is VERY powerful
Feedback
Just as a side note, if I was doing something like this, it would be very different, but I tried to keep it simple.
We're generally discouraged from extending from top level containers like JFrame, as stated, JFrame is not a simple component and you're not actually adding any new functionality to the class and in the process, locking yourself into a single use, there by reducing re-usability. Better to start with a JPanel as your base component and simply create an instance of JFrame or `JDialog or what ever top level container you want to use, when you need it
KeyListener is a poor choice for monitoring keyboard input (seriously, just do a search for "my key listener won't work". Instead, take a look at How to Use Key Bindings
You are creating a new instance of your Window class in your keyPressed(..) method, therefore your cursor update does not work:
new Window().updateCursor(Window.ACTIVE);
You need to pass your existing Window instance to your MainMenu class and call this instance.
Here's a working example:
Main App:
public class MyApp extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApp app = new MyApp();
app.setVisible(true);
}
});
}
private MyApp() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
// Create cursors
Cursor c1 = Util.getCursor("c1.png");
Cursor c2 = Util.getCursor("c2.png");
setCursor(c1);
JButton button1 = new JButton("Change to Cursor1");
button1.setActionCommand("c1");
button1.addActionListener(new MyActionListener(this));
JButton button2 = new JButton("Change to Cursor2");
button2.setActionCommand("c2");
button2.addActionListener(new MyActionListener(this));
add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.SOUTH);
}
}
ActionListener (handles the button clicks):
public class MyActionListener implements ActionListener {
private JFrame jFrame;
public MyActionListener(JFrame jFrame) {
this.jFrame = jFrame;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()){
case "c1":
jFrame.setCursor(Util.getCursor("c1.png"));
System.out.println("switch to c1");
break;
case "c2":
jFrame.setCursor(Util.getCursor("c2.png"));
System.out.println("switch to c2");
break;
}
}
}
Util (read cursor image):
public class Util {
public static Cursor getCursor(String fileName) {
BufferedImage img = null;
try {
img = ImageIO.read(Util.class.getResourceAsStream(fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
return Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0), fileName);
}
}
So I am making a space invaders clone. Originally I had no problem getting my game to work with a simple main class that created the frame, created the gameplay and started the thread.
But then I tried to implement a start menu and it all went to crap. The menu appears with success but the gameplay does not appear when I press start.
I am running out of ideas and I am completely stumped. I am somewhat new as well to SO, so if there is anything I left out, I appreciate any help.
Here is the original with no menu that worked fine:
public static void main(String[] args) {
JFrame frame = new JFrame("SpaceRaiders");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Gameplay gameplay = new Gameplay();
frame.add(gameplay);
frame.setVisible(true);
Thread t1 = new Thread(gameplay);
t1.start();
}
However, the moment I tried to implement a menu to then play the game, I am running into all sorts of trouble. I created a UI class as well as an actual "game" class like so:
public class UI {
JFrame frame, f2;
JPanel titrePanel, startButtonPanel, loadButtonPanel, p2;
JLabel nomJeu;
JButton startButton, loadButton;
Font fontTitre, fontStart;
Gameplay gameplay;
public void createUI(ChoixJeu cj) {
frame = new JFrame("SpaceRaiders");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
frame.getContentPane().setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//------------------ECRAN MENU---------------------
//Titre
titrePanel = new JPanel();
titrePanel.setBounds(100, 100, 400, 100);
titrePanel.setBackground(Color.BLUE);
Font fontTitre = new Font("Times New Roman", Font.BOLD, 50);
Font fontStart = new Font("Times New Roman", Font.PLAIN, 20);
nomJeu = new JLabel("SpaceRaiders");
nomJeu.setForeground(Color.white);
nomJeu.setFont(fontTitre);
titrePanel.add(nomJeu);
//Start button
startButtonPanel = new JPanel();
startButtonPanel.setBounds(200, 400, 200, 40);
startButtonPanel.setBackground(Color.BLACK);
startButton = new JButton("START");
startButton.setBackground(Color.BLACK);
startButton.setForeground(Color.WHITE);
startButton.setFont(fontStart);
startButton.setFocusPainted(false);
startButton.addActionListener(cj);
startButton.setActionCommand("start");
startButtonPanel.add(startButton);
//Load Button
loadButtonPanel = new JPanel();
loadButtonPanel.setBounds(200, 440, 200, 100);
loadButtonPanel.setBackground(Color.BLACK);
loadButton = new JButton("LOAD");
loadButton.setBackground(Color.BLACK);
loadButton.setForeground(Color.WHITE);
loadButton.setFont(fontStart);
loadButton.setFocusPainted(false);
titrePanel.add(nomJeu);
loadButtonPanel.add(loadButton);
frame.add(startButtonPanel);
frame.add(titrePanel);
//------------------ECRAN MENU FIN---------------------
frame.setVisible(true);
}
And the game class...
public class Jeu {
ChoixJeu cj = new ChoixJeu();
UI ui = new UI();
Ecrans e = new Ecrans(ui);
Gameplay gp;
public static void main(String[] args) {
new Jeu();
}
public Jeu() {
ui.createUI(cj);
Gameplay gameplay = new Gameplay();
this.gp = gameplay;
}
public class ChoixJeu implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
String yourChoice = ae.getActionCommand();
switch (yourChoice) {
case "start":
e.montrerEcranJeu();
new Thread(gp).start();
ui.frame.add(gp);
break;
default:
break;
}
}
}
}
I also tried to make a class/method that hides the menu panels
public void montrerEcranJeu() {
//Cache Menu
ui.titrePanel.setVisible(false);
ui.startButtonPanel.setVisible(false);
//Montre Jeu
// ui.frame.add(gameplay);
}
And just in case the Gameplay class. The run() method is at the bottom
public class Gameplay extends JPanel implements KeyListener, ActionListener, Runnable {
private Ship player = new Ship(new Point(200, 555));
Timer t = new Timer(5, this);
private ArrayList<Laser> lasers = new ArrayList<Laser>();
private int laserNb;
private boolean readytofire;
private boolean shot = false;
private ArrayList<Invader> invaders = new ArrayList<Invader>();
private boolean pause;
public Gameplay() {
super();
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
for (int j = 0; j < 80; j += 20) {
for (int i = 0; i < 20; i++) {
invaders.add(new Invader(5 + i * 30, j));
}
}
}
public boolean addLaser(Laser a) {
lasers.add(a);
return true;
}
public boolean addPlayer(Ship p) {
this.player = p;
return true;
}
#Override
public void keyTyped(KeyEvent ke) {
}
public void keyPressed(KeyEvent e) {
if (KeyEvent.VK_RIGHT == e.getKeyCode()) {
moveRight();
}
if (KeyEvent.VK_LEFT == e.getKeyCode()) {
moveLeft();
}
if (KeyEvent.VK_SPACE == e.getKeyCode()) {
shoot();
System.out.println("Space Action from Gameplay is working");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void moveRight() {
if (player.getCentre().getX() >= 580) {
player.setX(580);
} else {
double movement = player.getCentre().getX();
movement += 10;
player.setX(movement);
}
this.repaint();
}
public void moveLeft() {
if (player.getCentre().getX() <= 20) {
player.setX(20);
} else {
double movement = player.getCentre().getX();
movement -= 10;
player.setX(movement);
}
this.repaint();
}
public void shoot() {
shot = true;
if (readytofire) {
Point top = new Point(player.getTopX(), player.getTopY());
Laser laser = new Laser(top);
addLaser(laser);
}
}
public void moveShot() {
if (shot) {
for (Laser l : lasers) {
l.setY(l.getTopLeft().getY() - 1);
}
}
}
#Override
public void paint(Graphics g) {
setBackground(Color.black);
super.paint(g);
player.draw(g);
for (Laser l : lasers) {
l.draw(g);
}
for (Invader i : invaders) {
i.draw(g);
}
}
// public void paintComponent (Graphics g){
// Controle Thread
public void run() {
while (true) {
moveShot();
for (Invader i : invaders) {
i.moveAndUpdate();
}
// for (Invader i : invaders) {
// if (){
// System.out.println("YOU ARE DEAD!");
// }
// }
try {
Thread.sleep(10);
readytofire = true;
} catch (InterruptedException ex) {
Logger.getLogger(Gameplay.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
So, using null layouts is the beginning of your problems. I might recommend using CardLayout which is designed to help you dynamically switch between views. See How to Use CardLayout for more details. I'd also suggest taking the time to read through Laying Out Components Within a Container and finding one or more appropriate layouts to support your menu.
You're also making a lot of fundamental mistakes. Swing is not thread safe, so you should avoid updating the UI (or something the UI depends on) from outside the context of the EDT - see Concurrency in Swing for more information and How to Use Swing Timers for a possible solution.
As a general recommendation, you should avoid overriding paint and, in the case of classes which extend from JComponent, prefer paintComponent instead. You should also avoid call methods which might change the state of the component during a paint cycle, this can increase the number of repaint requests and degrade the performance of your program (ie, don't call setBackground inside paint).
Have a look at Performing Custom Painting and Painting in AWT and Swing for more details about how the paint system works and how best you can work with it.
You should also avoid KeyListener, this is likely to cause you issues when you introduce other, focusable, components into the picture. Instead, you should favour the Key bindings API instead
I've read through [insert link or tutorial], but it still doesn't help...
And forgive me if this doesn't happen all the time.
The point of providing you the tutorial links is to encourage you to learn something;
Learn where to find answers to your questions
Learn how the APIs work
Expand your knowledge and understanding of how the APIs work
Having said that, they're not always "obvious" as to the solution. What I do when I'm in this situation is start with one or more new projects, dedicated to just working on that aspect of the API I'm trying to understand. For here I can explore the concepts in isolation and when I "think" I understand them, try and implement them into the project I'm working on. This might take a number of iterations, but once it works, I have gained a much deeper understanding and appreciation of the API then I would have gained from a simple "copy-n-paste" solution
I'm developing a Java Swing app for an award winning password protection system, and I need a large custom cursor [ 80 x 80 ], you might ask why so large, there is an online web demo you may look at to learn why it needs to be so large : http://gatecybertech.net
That large cursor is used on the login page in the above link. Of course you need to create a test password first before you can try the login process.
But anyway, in my Swing app, I hit a limit of 32 x 32 for the largest possible custom cursor, my code looks like the following :
Image cursorImage = toolkit.getImage("Cursor_Crosshair.PNG");
Tabular_Panel.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(cursorImage,new Point(0,0),"custom cursor"));
The image size of Cursor_Crosshair.PNG is : 80 x 80
But what shows up in the screen is a shrinked version of it at : 32 x 32
So my question is : how can I bypass the size limit on customer cursor image, and make the cursor to show up at the size of 80 x 80 ?
I know the OS might be the reason for the limit, is there a way to overcome it ?
Here's my take on the glass pane painting approach. This is set up to behave pretty much like setting a custom cursor. The default "arrow" cursor is hidden while the custom cursor is shown, and the custom cursor is hidden when a component has some other cursor set, such as a text box.
Unfortunately, it ended up seeming to require quite a bit of Swing black magic, so I don't like it very much, but it does seem to work correctly. I've done a cursor like this before, but it was for something simpler, so I didn't run in to these issues.
Some of the problems I ran in to are:
The glass pane intercepts cursor changes (described e.g. on SO here). The only solution I've been able to find is to override Component.contains(int,int) to return false (described here, shown here), but why that works and doesn't seem to break anything else is mysterious.
Mouse exit events sometimes return a location inside the bounds of the component, so I don't think there's a reliable way to know when the mouse leaves the window except to use a timer.
package mcve;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.net.*;
import java.io.*;
public class LargeCursor {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
JPanel glass = new CustomGlassPane();
glass.add(new CursorPanel(), BorderLayout.CENTER);
frame.setGlassPane(glass);
// This next call is necessary because JFrame.setGlassPane delegates to the root pane:
// - https://docs.oracle.com/javase/9/docs/api/javax/swing/RootPaneContainer.html#setGlassPane-java.awt.Component-
// - http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/javax/swing/JFrame.java#l738
// And JRootPane.setGlassPane may call setVisible(false):
// - https://docs.oracle.com/javase/9/docs/api/javax/swing/JRootPane.html#setGlassPane-java.awt.Component-
// - http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/javax/swing/JRootPane.java#l663
glass.setVisible(true);
JPanel content = createTestPanel();
content.setCursor(BlankCursor.INSTANCE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
static class CustomGlassPane extends JPanel {
CustomGlassPane() {
super(new BorderLayout());
super.setOpaque(false);
}
#Override
public boolean contains(int x, int y) {
return false;
}
}
static class CursorPanel extends JPanel {
final BufferedImage cursorImage;
Point mouseLocation;
CursorPanel() {
try {
cursorImage = createTransparentImage(
ImageIO.read(new URL("https://i.stack.imgur.com/9h2oI.png")));
} catch (IOException x) {
throw new UncheckedIOException(x);
}
setOpaque(false);
long mask = AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK;
Toolkit.getDefaultToolkit().addAWTEventListener((AWTEvent e) -> {
switch (e.getID()) {
case MouseEvent.MOUSE_ENTERED:
case MouseEvent.MOUSE_EXITED:
case MouseEvent.MOUSE_MOVED:
case MouseEvent.MOUSE_DRAGGED:
capturePoint((MouseEvent) e);
break;
}
}, mask);
// This turned out to be necessary, because
// the 'mouse exit' events don't always have
// a Point location which is outside the pane.
Timer timer = new Timer(100, (ActionEvent e) -> {
if (mouseLocation != null) {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
if (!contains(p)) {
setMouseLocation(null);
}
}
});
timer.setRepeats(true);
timer.start();
}
void capturePoint(MouseEvent e) {
Component comp = e.getComponent();
Point onThis = SwingUtilities.convertPoint(comp, e.getPoint(), this);
boolean drawCursor = contains(onThis);
if (drawCursor) {
Window window = SwingUtilities.windowForComponent(this);
if (window instanceof JFrame) {
Container content = ((JFrame) window).getContentPane();
Point onContent = SwingUtilities.convertPoint(comp, e.getPoint(), content);
Component deepest = SwingUtilities.getDeepestComponentAt(content, onContent.x, onContent.y);
if (deepest != null) {
if (deepest.getCursor() != BlankCursor.INSTANCE) {
drawCursor = false;
}
}
}
}
setMouseLocation(drawCursor ? onThis : null);
}
void setMouseLocation(Point mouseLocation) {
this.mouseLocation = mouseLocation;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mouseLocation != null) {
int x = mouseLocation.x - (cursorImage.getWidth() / 2);
int y = mouseLocation.y - (cursorImage.getHeight() / 2);
g.drawImage(cursorImage, x, y, this);
}
}
}
static final class BlankCursor {
static final Cursor INSTANCE =
Toolkit.getDefaultToolkit().createCustomCursor(
new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB),
new Point(),
"BLANK");
}
static JPanel createTestPanel() {
JPanel panel = new JPanel(new GridLayout(3, 3));
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
for (int i = 0; i < 9; ++i) {
if ((i % 2) == 0) {
JTextField field = new JTextField("Text Field");
field.setHorizontalAlignment(JTextField.CENTER);
panel.add(field);
} else {
panel.add(new JButton("Button"));
}
}
return panel;
}
static BufferedImage createTransparentImage(BufferedImage img) {
BufferedImage copy =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration()
.createCompatibleImage(img.getWidth(),
img.getHeight(),
Transparency.TRANSLUCENT);
for (int x = 0; x < img.getWidth(); ++x) {
for (int y = 0; y < img.getHeight(); ++y) {
int rgb = img.getRGB(x, y) & 0x00FFFFFF;
int bright = (((rgb >> 16) & 0xFF) + ((rgb >> 8) & 0xFF) + (rgb & 0xFF)) / 3;
int alpha = 255 - bright;
copy.setRGB(x, y, (alpha << 24) | rgb);
}
}
return copy;
}
}
OK, after some research and modification, I found the answer :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.event.MouseInputAdapter;
public class Demo_Large_Custom_Cursor
{
static private MyGlassPane myGlassPane;
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame=new JFrame("Demo_Large_Custom_Cursor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Start creating and adding components.
JCheckBox changeButton=new JCheckBox("Custom Cursor \"visible\"");
changeButton.setSelected(false);
//Set up the content pane, where the "main GUI" lives.
Container contentPane=frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(changeButton);
JButton Button_1=new JButton("<Html><Table Cellpadding=7><Tr><Td>A</Td><Td>B</Td></Tr><Tr><Td>C</Td><Td>D</Td></Tr></Table></Html>");
Button_1.setPreferredSize(new Dimension(80,80));
Button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Out("Button 1"); } });
contentPane.add(Button_1);
JButton Button_2=new JButton("<Html><Table Cellpadding=7><Tr><Td>1</Td><Td>2</Td></Tr><Tr><Td>3</Td><Td>4</Td></Tr></Table></Html>");
Button_2.setPreferredSize(new Dimension(80,80));
Button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Out("Button 2"); } });
contentPane.add(Button_2);
//Set up the menu bar, which appears above the content pane.
JMenuBar menuBar=new JMenuBar();
JMenu menu=new JMenu("Menu");
menu.add(new JMenuItem("Do nothing"));
menuBar.add(menu);
frame.setJMenuBar(menuBar);
//Set up the glass pane, which appears over both menu bar
//and content pane and is an item listener on the change
//button.
myGlassPane=new MyGlassPane(changeButton,menuBar,frame.getContentPane());
changeButton.addItemListener(myGlassPane);
frame.setGlassPane(myGlassPane);
//Show the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
/**
We have to provide our own glass pane so that it can paint.
*/
class MyGlassPane extends JComponent implements ItemListener
{
Point point;
//React to change button clicks.
public void itemStateChanged(ItemEvent e)
{
setVisible(e.getStateChange()==ItemEvent.SELECTED);
}
protected void paintComponent(Graphics g)
{
try
{
if (point!=null)
{
// g.setColor(Color.red);
// g.fillOval(point.x-10,point.y-10,20,20);
BufferedImage image=ImageIO.read(new File("C:/Cursor_Crosshair.PNG"));
g.drawImage(image,point.x-39,point.y-39,null);
}
}
catch (Exception e) { }
}
public void setPoint(Point p)
{
point=p;
}
public MyGlassPane(AbstractButton aButton,JMenuBar menuBar,Container contentPane)
{
CBListener listener=new CBListener(aButton,menuBar,this,contentPane);
addMouseListener(listener);
addMouseMotionListener(listener);
}
}
/**
Listen for all events that our check box is likely to be interested in. Redispatch them to the check box.
*/
class CBListener extends MouseInputAdapter
{
Toolkit toolkit;
Component liveButton;
JMenuBar menuBar;
MyGlassPane glassPane;
Container contentPane;
public CBListener(Component liveButton,JMenuBar menuBar,MyGlassPane glassPane,Container contentPane)
{
toolkit=Toolkit.getDefaultToolkit();
this.liveButton=liveButton;
this.menuBar=menuBar;
this.glassPane=glassPane;
this.contentPane=contentPane;
}
public void mouseMoved(MouseEvent e)
{
// redispatchMouseEvent(e,false);
redispatchMouseEvent(e,true);
}
public void mouseDragged(MouseEvent e)
{
redispatchMouseEvent(e,false);
}
public void mouseClicked(MouseEvent e)
{
redispatchMouseEvent(e,false);
}
public void mouseEntered(MouseEvent e)
{
redispatchMouseEvent(e,false);
}
public void mouseExited(MouseEvent e)
{
redispatchMouseEvent(e,false);
}
public void mousePressed(MouseEvent e)
{
redispatchMouseEvent(e,false);
}
public void mouseReleased(MouseEvent e)
{
redispatchMouseEvent(e,true);
}
//A basic implementation of redispatching events.
private void redispatchMouseEvent(MouseEvent e,boolean repaint)
{
Point glassPanePoint=e.getPoint();
Container container=contentPane;
Point containerPoint=SwingUtilities.convertPoint(glassPane,glassPanePoint,contentPane);
if (containerPoint.y<0)
{ //we're not in the content pane
if (containerPoint.y+menuBar.getHeight()>=0)
{
//The mouse event is over the menu bar.
//Could handle specially.
}
else
{
//The mouse event is over non-system window
//decorations, such as the ones provided by
//the Java look and feel.
//Could handle specially.
}
}
else
{
//The mouse event is probably over the content pane.
//Find out exactly which component it's over.
Component component=SwingUtilities.getDeepestComponentAt(container,containerPoint.x,containerPoint.y);
// if ((component!=null) && (component.equals(liveButton)))
if ((component!=null))
{
//Forward events over the check box.
Point componentPoint=SwingUtilities.convertPoint(glassPane,glassPanePoint,component);
component.dispatchEvent(new MouseEvent(component,e.getID(),e.getWhen(),e.getModifiers(),componentPoint.x,componentPoint.y,e.getClickCount(),e.isPopupTrigger()));
}
}
//Update the glass pane if requested.
if (repaint)
{
glassPane.setPoint(glassPanePoint);
glassPane.repaint();
}
}
}
And the Cursor_Crosshair.PNG is like this :
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.
I never get "paint" written to my command line window when I use Eclipse and Run->cmd to run the program. It works fine if I run System.out.print() from paintComponent in another program. Someone who can help?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JPanel implements KeyListener, ActionListener
{
private static final long serialVersionUID = 1L;
JFrame frmMain = new JFrame("Kodning");
JTextField text = new JTextField();
JPanel pan = new JPanel();
static char bokstav;
static int x=10, y=80;
boolean convert = false;
String s;
Timer t = new Timer(10, this);
public static void main(String[] args)
{
#SuppressWarnings("unused")
GUI g = new GUI();
}
public GUI()
{
frmMain.setSize(600, 120);
frmMain.setLayout(new GridLayout(2, 1));
frmMain.addWindowListener(hornStang());
frmMain.add(text);
frmMain.add(pan);
frmMain.setFocusable(true);
frmMain.setVisible(true);
frmMain.addKeyListener(this);
text.addKeyListener(this);
pan.addKeyListener(this);
t.start();
}
private static WindowAdapter hornStang()
{
return new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()== KeyEvent.VK_ENTER)
{
System.out.println("dechifrera");
repaint();
deshiffrera(text.getText());
}
}
public void keyReleased(KeyEvent arg0){}
public void keyTyped(KeyEvent arg0){}
public void deshiffrera(String s)
{
s = this.s;
repaint();
}
#override
public void paintComponent(Graphics g)
{
System.out.println("paint");
for(int i=0;i<s.length();i++)
{
bokstav = s.charAt(i);
switch (bokstav)
{
case 'a':nere(g); hoger(g); prick(g, 0); break;
//en massa case
default:break;
}
x=x+12;
}
}
#Override
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
The component must be added to a visible window/frame/component for it's paintComponent to be called.
GUI is only added as a KeyListener but is neither added to the JFrame, nor any other visible component in the code above. There is no reason for calling paintComponent since the component is not being displayed at all.
There are a number of issues with your code:
Your GUI panel is not in the frame (shouldn't it be added instead of pan?)
String s is uninitialized, which causes a NullPointerException
paint should be overridden instead of paintComponents
paint should not change the state of the component, because it can be called any time.
etc...
You probably miss the output of "System.out.println("paint");" ?
GUI-Apps under Windows cant write to the console (they dont have a console, because it would suck if every GUI-App would also open a black window).
There are two java-interpreters under windows: "javaw.exe" which is a GUI-App and silently discards any System.out-writes. And "java.exe" which is a console-app and allows writing to the console. Try to start your program with "java.exe"
I use this with AWT (not 100% sure whether it's working in Swing too...)
Graphics g = _yourcomponent_.getGraphics();
if (g != null) {
_yourcomponent_.paint(g);
// below the estimated code for Swing:
_yourcomponent_.paintComponent(g);
}