awt
Changing cursor shape when hovering over components
In this example we are going to see how to change the shape of the cursor when hovering over components. This will create an impressive and practical graphic for your application, which will notify the users that they are pointing to an object with some certain functionality.
In short, all you have to do in order to change the cursor shape when hovering over components is:
- Create a new
Frame
an a newPanel
. - Create a number of components like
Buttons
. - Use
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
to set the hand cursor when hovering this element. - Use
button.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))
to set the waiting cursor when hovering this element.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Component; import java.awt.Cursor; import java.awt.Frame; import java.awt.Panel; import java.awt.TextArea; public class ComponentCursorExample { public static void main(String[] args) { // Create a frame Frame frame = new Frame("Example Frame"); /** * Create a container with a flow layout, which arranges its children * horizontally and center aligned. * A container can also be created with a specific layout using * Panel(LayoutManager) constructor, e.g. * Panel(new FlowLayout(FlowLayout.RIGHT)) for right alignment */ Panel panel = new Panel(); Button buttonA = new Button("Button_A"); Button buttonB = new Button("Button_B"); Button buttonC = new Button("Button_C"); // By default, the component's cursor is Cursor.DEFAULT_CURSOR // Change the buttons cursor to another shape buttonB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); buttonC.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Add several buttons to the container panel.add(buttonA); panel.add(buttonB); panel.add(buttonC); // Add a text area in the center of the frame Component textArea = new TextArea("This is a sample text..."); frame.add(textArea, BorderLayout.CENTER); // Add the container to the bottom of the frame frame.add(panel, BorderLayout.SOUTH); // Display the frame int frameWidth = 300; int frameHeight = 300; frame.setSize(frameWidth, frameHeight); frame.setVisible(true); } }
This was an example on how to change cursor shape when hovering over components.