当用户将鼠标移动到 Java Swing JDialog 中的某个文本上时,让自定义光标出现


首先设置一个标签,在标签上面将鼠标悬停时,会显示自定义光标

JLabel label = new JLabel("Demo text! Hand cursor is visible on hover...");

现在,设置光标为手形光标,而不是默认光标

label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

以下是一个示例,当用户将鼠标移动到某些文本时,会显示一个自定义光标

示例

import java.awt.Cursor;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class SwingDemo extends JFrame {
   private void ShowDialog() {
      JLabel label = new JLabel("Demo text! Hand cursor is visible on hover...");
      label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      JOptionPane pane = new JOptionPane(label);
      pane.setOptions(new Object[] { "Close" });
      JDialog dialog = pane.createDialog(this, "Info");
      dialog.setVisible(true);
   }
   public static void main(String[] args) {
      SwingDemo demo = new SwingDemo();
      demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      demo.setSize(600, 450);
      demo.setVisible(true);
      demo.ShowDialog();
   }
}

输出如下。当您将光标保持在 Dialog 文本“示例文本!鼠标悬停时,手形光标可见...”下时,光标会转换为手形光标

输出

更新日期:2019 年 7 月 30 日

569 次浏览

开启您的职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.