setCursor method does not work -- Pls help
807589Aug 3 2008 — edited Aug 4 2008I want to change the mouse pointer when the mouse enters a JPanel to indicate that a specific drawing operation is now applicable. However, the following code seems not working properly. The desired cursor just does not show up!!! I'm using J2SE version 6 update 5 (build 1.6.0_05-b13). The image "curRectA" is a 24 by 24 256 color gif image. Could you guys please give me some advice? Thanks a lot!
Below is the code I have been using.
/*
* NewJDialog.java
*
* Created on August 3, 2008, 2:39 PM
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Cursor;
/**
*
* @author william
*/
class MouseHandler extends MouseAdapter {
public MouseHandler() {
}
public void mouseEntered(MouseEvent evt) {
JPanel srcPanel = (JPanel)evt.getSource();
javax.swing.ImageIcon curS;
java.awt.Toolkit kit = java.awt.Toolkit.getDefaultToolkit();
java.net.URL imgURL = getClass().getResource("curRectA.gif");
if (imgURL != null) {
curS = new javax.swing.ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: curRectA.gif");
return;
}
java.awt.Image imageCursor=curS.getImage();
Cursor customCursor=kit.createCustomCursor(imageCursor,new java.awt.Point(),"MyCursor");
srcPanel.setCursor(customCursor);
}
}
public class NewJDialog extends javax.swing.JDialog {
/** Creates new form NewJDialog */
public NewJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
Dimension d = new Dimension(100, 100);
this.setSize(d);
mouseHandler = new MouseHandler();
jpanel = new JPanel();
jpanel.addMouseListener(mouseHandler);
getContentPane().add(jpanel, BorderLayout.CENTER);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private JPanel jpanel;
private MouseHandler mouseHandler;
}