在程序中禁用鼠标光标

Disable the mouse cursor within a program

我正在创建文字冒险,我需要完全禁用鼠标光标。不只是隐藏它,虽然我已经知道该怎么做,但要完全禁用它所以你必须使用 Alt-Tab 或内置的退出按钮来停止。这样做的主要原因是因为人们可以使用鼠标光标滚动,而我需要禁用它,我考虑过在 MouseEvents 被触发时取消它,但我无法让它工作(即监听器。)

如果有人知道怎么做请大声告诉我! :)


编辑: 糟糕,我忘记了我的代码。 Here is my Console class. 这是由另一个 class 和 new Console();

发起的

编辑 2: 以下是我尝试创建不可见光标和鼠标侦听器的一些片段。第一个有效,但后者无效。

// Invisible cursor
Toolkit toolkit = Toolkit.getDefaultToolkit();
Point hotSpot = new Point(0,0);
BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT); 
Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, "InvisibleCursor");        
frame.setCursor(invisibleCursor);

// Adding mouse listener
frame.addMouseListener(new MouseAdapter() { 
      public void mousePressed(MouseEvent me) { 
        System.out.println(me); 
      } 
});

编辑 3: 详细说明鼠标侦听器,它根本不起作用。它不打印任何东西。

如果您只想防止用户看到旧文本,请从 JTextArea 中删除旧文本。

最简单的方法是将 JTextArea 留在 JScrollPane 中,并自己跟踪行:

private static final int MAX_VISIBLE_LINES = 12;

private final Deque<String> lines = new LinkedList<>();

void appendLine(String line,
                JTextArea textArea) {

    lines.addLast(line);
    if (lines.size() > MAX_VISIBLE_LINES) {
        lines.removeFirst();
    }

    String text = String.join("\n", lines);
    textArea.setText(text);

    textArea.setCaretPosition(text.length());
    try {
        textArea.scrollRectToVisible(
            textArea.modelToView(text.length()));
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
}

试图在多任务桌面上霸占鼠标只会让用户生气。您想要一个阻止您阅读电子邮件的应用程序吗?

更新:

如果要根据 JTextArea 的当前高度确定文本行数,请使用 JTextArea 的字体规格。我假设你不需要完全正确,如果数字相差一两行也没关系。 (考虑换行之类的事情要困难得多。)

private final Deque<String> lines = new LinkedList<>();

void appendLine(String line,
                JTextArea textArea) {

    FontMetrics metrics = textArea.getFontMetrics(textArea.getFont());

    JViewport viewport = (JViewport) textArea.getParent();
    int visibleLineCount = viewport.getExtentSize().height / metrics.getHeight();

    lines.addLast(line);
    while (lines.size() > visibleLineCount) {
        lines.removeFirst();
    }

    String text = String.join("\n", lines);
    textArea.setText(text);

    textArea.setCaretPosition(text.length());
    try {
        textArea.scrollRectToVisible(
            textArea.modelToView(text.length()));
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
}