杰瑞科技汇

Java setcursor如何使用?

Of course! In Java, the concept of "setting the cursor" is handled differently depending on whether you're working with a Swing GUI or a console application.

Java setcursor如何使用?-图1
(图片来源网络,侵删)

Here’s a complete breakdown of both scenarios.


For Swing GUI Applications (JComponent)

In a Swing GUI, you set the cursor for a specific component (like a JFrame, JPanel, or JButton). The cursor is represented by the java.awt.Cursor class.

Key Methods:

  • Component.setCursor(Cursor cursor): This is the main method you'll use. It sets the cursor for the specified component and all of its sub-components.
  • Cursor.getPredefinedCursor(int type): This is the easiest way to get a standard cursor. You use one of the many Cursor constants like Cursor.HAND_CURSOR, Cursor.TEXT_CURSOR, etc.
  • Toolkit.getDefaultToolkit().createCustomCursor(...): To create your own custom cursor from an image.

Example: Setting a Hand Cursor on a Button

This is a very common use case. When you hover over a button, you want the cursor to change to a hand to indicate it's clickable.

import javax.swing.*;
import java.awt.*;
public class CursorExample {
    public static void main(String[] args) {
        // Create a new JFrame (window)
        JFrame frame = new JFrame("Cursor Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLayout(new FlowLayout());
        // Create a button
        JButton myButton = new JButton("Hover over me!");
        // --- THIS IS THE KEY PART ---
        // Get the predefined hand cursor and set it for the button
        Cursor handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
        myButton.setCursor(handCursor);
        // ---------------------------
        // Add the button to the frame
        frame.add(myButton);
        // Make the window visible
        frame.setVisible(true);
    }
}

Common Predefined Cursor Types:

Constant Description Icon
DEFAULT_CURSOR The default cursor (usually an arrow). ↖️
CROSSHAIR_CURSOR A crosshair.
TEXT_CURSOR An I-beam, used for text. I
WAIT_CURSOR An hourglass or a spinning circle.
HAND_CURSOR A hand, often used for links or buttons. 👆
MOVE_CURSOR A cross with arrows, indicating movement.
RESIZE_CURSOR A double-headed arrow, indicating resizing. 🔄
N_RESIZE_CURSOR North-resizing arrow. ⬆️
S_RESIZE_CURSOR South-resizing arrow. ⬇️
E_RESIZE_CURSOR East-resizing arrow. ➡️
W_RESIZE_CURSOR West-resizing arrow. ⬅️

Example: Changing the Cursor for the Whole Window

If you want the cursor to change for the entire JFrame, you call setCursor() directly on the frame object.

Java setcursor如何使用?-图2
(图片来源网络,侵删)
// Inside your JFrame setup...
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
// Set the cursor for the entire window to a wait cursor
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Add components...
JLabel label = new JLabel("Please wait...");
frame.add(label, BorderLayout.CENTER);
frame.setVisible(true);

For Console Applications (Standard Output)

In a standard console (command prompt or terminal), you cannot directly "set the cursor" to an arbitrary (x, y) position using standard Java. The console is a simple line-oriented output stream.

However, you can achieve this effect on specific operating systems using platform-specific commands. This is generally not recommended for portable applications.

The "Portable" (but Limited) Way: \r (Carriage Return)

You can use the carriage return character (\r) to move the cursor to the beginning of the current line. This allows you to overwrite the line. This is the standard way to create simple progress bars or status updates.

public class ConsoleCursorExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Starting process...");
        for (int i = 0; i <= 100; i++) {
            // \r moves the cursor to the start of the line
            // The printf formats the number to be 3 digits wide, making the bar stable
            System.out.printf("\rProgress: %3d%%", i);
            // Flush the output to ensure it's displayed immediately
            System.out.flush();
            // Simulate work
            Thread.sleep(50);
        }
        // Print a newline to move to the next line after the loop finishes
        System.out.println("\nProcess complete!");
    }
}

Output in your console:

Starting process...
Progress: 100%
Process complete!

The line Progress: ... will be updated in place.

The Non-Portable (OS-Specific) Way

If you absolutely need full cursor control, you can execute system commands. This is not recommended for production code as it will fail on other operating systems.

For Windows (using cmd.exe commands):

public class WindowsConsoleCursor {
    public static void main(String[] args) {
        try {
            // Clear the screen
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            // Move cursor to row 5, column 10
            // The syntax is: \033[y;xH where y is row and x is column
            // Note: Windows cmd uses a different escape sequence.
            // The modern way is to use ANSI codes, which newer Windows 10/11 terminals support.
            System.out.print("\033[5;10H"); // Move to row 5, column 10
            System.out.println("Hello at (5, 10)");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

For Linux/macOS (using ANSI escape codes): Most modern terminals (including the one in VS Code and modern macOS/Linux) understand ANSI escape codes. This is a more robust way to control the console if you're targeting non-Windows systems.

public class AnsiConsoleCursor {
    public static void main(String[] args) {
        // ANSI Escape Codes:
        // \033[<row>;<column>H  -> Move cursor to (row, column)
        // \033[2J              -> Clear the entire screen
        // \033[K               -> Clear the rest of the line
        // Clear screen and move cursor to top-left
        System.out.print("\033[2J\033[H");
        System.out.println("Screen cleared. Cursor at (1,1)");
        // Move cursor to row 10, column 20
        System.out.print("\033[10;20H");
        System.out.println("Hello at (10, 20)");
    }
}

Summary

Environment Method Key Classes/Concepts Portability
Swing GUI component.setCursor(Cursor.getPredefinedCursor(...)) java.awt.Cursor, java.awt.Component Excellent. Standard for all Java GUIs.
Console Overwriting with \r and printf System.out, Thread.sleep() Good. Works on all platforms but limited.
Console Platform-specific commands or ANSI codes ProcessBuilder, ANSI escape sequences (\033[...) Poor. Not portable; use with extreme caution.
分享:
扫描分享到社交APP
上一篇
下一篇