java - 如何以编程方式将 shift 键应用于字符?

标签 java javafx unicode keyboard

我正在尝试实现等效于键盘“shift”键的功能,当按下该键时,会将 UI 文本更新为大写字母,或者例如“@”而不是 2。

我已经尝试了 toCapital 和 toLowerCase 函数,但它们似乎不适用于可以说是两者中更重要的符号。

并不是真的需要代码来帮助我回答这个问题,但这是我想要发生的事情的简单伪代码布局

UI Element x;
UI Element five;
five.setText("5");
x.setText("x");

// Hopefully this shifting function would return
applyShift(x.getText()) == 'X' TRUE
applyShift(five.getText()) == '%' TRUE

// and if we were to apply shift again they would go back to their original values

Does a function like this exist?

最佳答案

我认为您最接近的可能是为您想要支持的每个键盘布局创建一个不同的映射,并自己手动设置键值对。

这不是一项微不足道的任务,因为您需要考虑未知数量的键盘布局,但如果您只打算支持一些布局,这可能会奏效。

这是一个简单的例子:

import java.util.HashMap;
import java.util.Map;

enum KeyboardLayout {
    // Would need to include additional supported keyboard layouts here.
    QWERTY
}

class Scratch {
    public static void main(String[] args) {
        String input = "Hello123";

        System.out.println(applyShift(input, getShiftMap(KeyboardLayout.QWERTY)));

    }

    private static String applyShift(String string, Map shiftMap) {

        StringBuilder sb = new StringBuilder();

        for (char c : string.toCharArray()) {

            // If a "shifted" value exists, use it, otherwise keep the original char
            if (shiftMap.get(c) != null) {
                sb.append(shiftMap.get(c));
            } else {
                sb.append(c);
            }
        }

        return sb.toString();

    }

    private static Map<Character, Character> getShiftMap(KeyboardLayout layout) {

        // Map to hold our entire keyboard layout
        Map<Character, Character> shiftMap = new HashMap<>();

        // Here we would need to map each and every key that has a "shifted" value. Capital letters would not need to
        // be accounted for as they are already "shifted"
        switch (layout) {
            case QWERTY:
                shiftMap.put('h', 'H');
                shiftMap.put('e', 'E');
                shiftMap.put('l', 'L');
                shiftMap.put('o', 'O');
                shiftMap.put('1', '!');
                shiftMap.put('2', '@');
                shiftMap.put('3', '#');
                // Etc, etc, etc
        }

        return shiftMap;
    }
}

此示例的打印输出是 HELLO!@#


为了处理相反的情况(找到 UN-shifted 字符),您需要创建和维护另一个 Map,或者使用第 3 方 API,例如 Google 的 Guava 库和他们的 BiMap .

关于java - 如何以编程方式将 shift 键应用于字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404233/

相关文章:

java - 导致 TestNG 测试失败?

gradle - 我正在使用javafx-gradle-plugin,构建失败并显示 “Couldn'找不到Ant-JavaFX-library。如何指定JavaFX位置?

python - 通过 python-ldap 使用 Active Directory 中的 unicode 编码字符串

python - 使用 Python 插入 MongoDB 的编码问题

java - JSF Servlet 导致奇怪的行为

java - 如何使用 JSF/MyFaces 创建基于用户角色的条件?

android - 在 Android 上同时使用 JavaFx + Activity

java - 无法在新场景中移动 TextFlow

python - CSV、Python : Using DictWriter correctly (ValueError: dict contains fields not in fieldnames)

java - JFace 仅调整 TitleAreaDialog 中最后一组的大小