我的情况是我必须在文本字段中扫描一个qrcode,我必须解析它与非printables字符(顺便说一下,它总是相同的字符),它们永远不会出现在相同的位置。
我尝试获取此代码但没有成功
我使用KeyBindings
成功,然后用字形替换为@trashgod注释。
示例:
public class Test {
private JPanel panel;
private JTextArea textArea;
public static final String GS_UNICODE = "\u241D";
public Test(){
panel = new JPanel();
textArea = new JTextArea(10,30);
final JTextField textfield = new JTextField(30);
textfield.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_F8,0), "test");
textfield.getActionMap().put("test", new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
textfield.setText(textfield.getText()+GS_UNICODE);
}
});
textfield.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText(textfield.getText());
}
});
panel.add(textfield);
JButton button = new JButton("Press non-readable");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
textfield.requestFocusInWindow();
robot.setAutoDelay(10);
robot.keyPress(KeyEvent.VK_F8);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_ENTER);
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
//check if string has glyph
System.out.println(textfield.getText().contains(GS_UNICODE));
System.out.println(textfield.getText());
}
});
} catch (AWTException ex) {
ex.printStackTrace();
}
}
});
panel.add(button);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("DataMatrix example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
Test example =new Test();
frame.add(example.panel,BorderLayout.CENTER);
frame.add(example.textArea,BorderLayout.SOUTH);
//Display the window.
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
但我的问题是:
1)有没有办法通过textcomponent(aka Document)的底层模型而不是KeyBinding捕获不可打印的ASCII代码(n <31和n = 127),而不是像textfield.setText(textfield.getText()+"myReplacement");
这样的字形替换。例如,在带有正则表达式&#34; \ p {Cntrol}&#34;
2)假设KeyBinding是正确的方法,如果我必须听所有不可打印的字符,是否有一种自动方式用其字形改变该代码?