Since time, it was my tiny dream to set my own custom image cursor for a swing component and now I am able to do that in a single line! What have I done is I have been searching for a method in the
Cursor
class so was unable to find. I asked myself how did I forget the Toolkit
class that has createCustomCursor() which takes just three parameters, the Image
object, hotspot point and cursor description. Fine, let us stop talking about this, and see the program.
public Cursor createCustomCursor(Image cursor,Point hotspot,String desc) throws IndexOutOfBoundsException, HeadlessException
import javax.swing.*;
import java.awt.*;
class CustomImageCursor extends JFrame
{
public CustomImageCursor()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Image Cursor");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(new JButton("Button"));
add(new JCheckBox("Checkbox"));
try
{
setCursor(Toolkit.getDefaultToolkit().createCustomCursor(new ImageIcon("mycursor1.png").getImage(),new Point(0,0),"custom cursor"));
}catch(Exception e){}
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new CustomImageCursor();
}
});
}
}
No comments:
Post a Comment