Search code examples
javaswingkeyboardjframejtextfield

How to program java virtual keyboard for touchscreen?


I've found many solutions on web about, but none is suitable for my problem. I have in a JFrame a KeyBoard that, on click, writes in a JTextField which is in another JFrame. The keyboard appears thanks to an OnClickEvent in a JText, something like iphone keyboard. How can I link the buttons to the JTextField in the other frame?


Solution

  • First your Swing keyboard needs to know where to pass the values. Add a JTextComponent field variable and a setter for it:

    private JTextComponent textComponent;
    

    JTextComponent is the base class for JTextField, JTextArea, etc ...

    Then you need to write an ActionListener that handles the actions:

    private class KeyboardActionListener implements ActionListener {
    
        public void actionPerformed(ActionEvent e) {
            try {
                JButton key = (JButton) e.getSource();
                textComponent.getDocument().insertString(textComponent.getCaretPosition(), key.getText(), null);
            } catch (BadLocationException ex) {
                Logger.getLogger(KeyboardDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

    Third step is to add all your buttons to that action listener. When a button is clicked, it will get the button from the ActionEvent, and insert its value at the current carret position. Keep in mind that this will not handle function keys. For that, have a look at JTextComponent.