【问题标题】:JTextField - Moving cursor using a buttonJTextField - 使用按钮移动光标
【发布时间】:2014-10-18 12:47:42
【问题描述】:

我真的很难找到功能(如果它存在的话), 通过单击 Button 而不是使用鼠标来移动 JTextFields 光标。

例如,我的文本字段添加了一个字符串。 通过单击后退按钮,光标将在字符串中向后移动,一次移动 1 个位置或向前移动,具体取决于按下的按钮。

我可以用鼠标来完成,只需单击并键入,但我实际上需要基于按钮,以便用户可以选择使用键盘输入名称或只需单击 JTextArea 并键入即可.

有可能吗?如果是,我应该寻找什么方法。

谢谢。

【问题讨论】:

    标签: java swing jbutton jtextfield


    【解决方案1】:

    这些是执行您要求的示例按钮:

    btnMoveLeft = new JButton("-");
    btnMoveLeft.setFocusable(false);
    btnMoveLeft.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left
      }
    });
    // omitted jpanel stuff
    
    btnmoveRight = new JButton("+");
    btnmoveRight.setFocusable(false);
    btnmoveRight.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right
      }
    });
    // omitted jpanel stuff
    

    他们在文本字段 txtAbc 中移动胡萝卜,每次点击 1 个位置。请注意,您需要禁用这两个按钮的 focusable 标志,否则如果您单击其中一个按钮,您的文本字段的焦点将会消失并且您再也看不到胡萝卜了。

    为避免在您尝试将胡萝卜移出文本字段边界(-1 或大于文本长度)时出现异常,您应该检查新值(例如在专用方法中):

    private void moveLeft(int amount) {
        int newPosition = txtAbc.getCaretPosition() - amount;
        txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition);
    }
    
    private void moveRight(int amount) {
        int newPosition = txtAbc.getCaretPosition() + amount;
        txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition);
    }
    

    【讨论】:

    • 这正是我想要的。现在我可以使用按钮浏览 texfield。非常感谢!构建计算器并需要使用键盘和按钮编辑字段。谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    相关资源
    最近更新 更多