aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornea <romangraef@gmail.com>2021-10-30 03:14:28 +0200
committernea <romangraef@gmail.com>2021-10-30 03:14:28 +0200
commit6938673c35a844b722611f15a95def25be3f25f1 (patch)
tree14335592fe015673509ec8e3e7b9c4c1987bbd43
parent70447a8719b6d8d5ad3ac0da2a5610eef77df9c4 (diff)
downloadLibGui-6938673c35a844b722611f15a95def25be3f25f1.tar.gz
LibGui-6938673c35a844b722611f15a95def25be3f25f1.tar.bz2
LibGui-6938673c35a844b722611f15a95def25be3f25f1.zip
Make caret position movable by clicks
Also deprecated the public getCaretPos method since it was public.
-rw-r--r--src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java21
1 files changed, 20 insertions, 1 deletions
diff --git a/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java b/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java
index c0ef7c2..3ea2123 100644
--- a/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java
+++ b/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java
@@ -127,6 +127,7 @@ public class WTextField extends WWidget {
return this.cursor;
}
+ @Environment(EnvType.CLIENT)
public void scrollCursorIntoView() {
if (scrollOffset > cursor) {
scrollOffset = cursor;
@@ -322,12 +323,29 @@ public class WTextField extends WWidget {
@Override
public InputResult onClick(int x, int y, int button) {
requestFocus();
- cursor = getCaretPos(this.text, x - TEXT_PADDING_X);
+ cursor = getCaretPosition(x - TEXT_PADDING_X);
scrollCursorIntoView();
return InputResult.PROCESSED;
}
@Environment(EnvType.CLIENT)
+ public int getCaretPosition(int clickX) {
+ if (clickX < 0) return 0;
+ int lastPos = 0;
+ String string = text.substring(scrollOffset);
+ for (int i = 0; i < string.length(); i++) {
+ int w = font.getWidth(string.charAt(i) + "");
+ if (lastPos + w >= clickX) {
+ if (clickX - lastPos < w / 2) {
+ return i + scrollOffset;
+ }
+ }
+ lastPos += w;
+ }
+ return string.length();
+ }
+
+ @Environment(EnvType.CLIENT)
@Override
public void onCharTyped(char ch) {
if (this.text.length() < this.maxLength) {
@@ -474,6 +492,7 @@ public class WTextField extends WWidget {
* @return
*/
@Environment(EnvType.CLIENT)
+ @Deprecated
public static int getCaretPos(String s, int x) {
if (x <= 0) return 0;