如果不是keyEvents,我应该为屏幕键盘使用什么事件监听器? [英] What event listener should I use for on-screen keyboard if not keyEvents?

查看:60
本文介绍了如果不是keyEvents,我应该为屏幕键盘使用什么事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的java swing程序中有一个类似这样的代码:

I have a code that goes like this in my java swing program:

  JTextField textfield = (JTextField) txtNameID.getEditor().getEditorComponent();
  textfield.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent ke) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    comboFilter(textfield.getText());
                }
            });
        }
    });

它的功能是显示数据库中的名称,就像在文本字段上键入的名称一样.用户开始输入后,它就会显示出来.

It's function is to show names from database that's like what is being typed on the textfield. It should show up once the user started typing.

赞:

这在使用硬键盘时效果很好.但是我的问题是我必须为此程序使用屏幕键盘/虚拟键盘,并且KeyListener不能使用它.现在,我不知道应该使用哪种类型的事件侦听器.我尝试了MouseListener,但它也无法正常工作.我希望有办法.我的项目真的需要这个.请帮我.

And this works well when using hard keyboard. But my problem is I have to use an on screen keyboard/virtual keyboard for this program and KeyListener doesn't work with it. Now I don't know what type of event listener I should use. I tried MouseListener but it doesn't work also. I hope there is a way. I really need this for my project. Please kindly help me out.

这是我在屏幕键盘上的代码(在同一班上,在其他班上有更长的代码):

This is my code for the on-screen keyboard(on the same class, it has a longer code in a different class):

   textfield.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
                  DialogVirtualKeyboardReal dlg = new DialogVirtualKeyboardReal(this, false, textfield);
                     dlg.setLocaleL(locale);
        }
    });
    
     textfield.addMouseListener(new MouseListener() {

        @Override
        public void mousePressed(MouseEvent me) {
            DialogVirtualKeyboardReal dlg = new DialogVirtualKeyboardReal(r, false, textfield);
                     dlg.setLocaleL(locale);
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            
        }

        @Override
        public void mouseEntered(MouseEvent me) {
          
        }

        @Override
        public void mouseExited(MouseEvent me) {
           
        }

        @Override
        public void mouseClicked(MouseEvent me) {
            
        }
    });
    

下面是DialogVirtualKeyboardReal的图片:

Here's a picture of the DialogVirtualKeyboardReal:

按键由JButton制成.

The keys are made of JButtons.

我按照@Abra的说明尝试了DocumentListener.

EDITED: I tried DocumentListener following the instructions of @Abra.

弹出键盘,但是在文本字段中键入1个字母并弹出下面的名称后,键盘消失.

The keyboard pops up, but it disappears after 1 letter typed in the textfield and the names below the textfield pops up.

即使我从虚拟键盘键入内容,也可以显示comboFilter.但是我希望它能够同时执行,在虚拟键盘上键入时,应该会出现comboFilter.

It's good that the comboFilter appears even when I type from virtual keyboard. But I want it to execute simultaneously, while typing on the virtual keyboard, the comboFilter should appear.

另一件事是我的数据库有错误.

Another thing is that it had an error with my database.

这是我创建的代码:

     JTextField textfield = (JTextField) txtNameID.getEditor().getEditorComponent();
   textfield.getDocument().addDocumentListener(new DocumentListener(){

        @Override
        public void insertUpdate(DocumentEvent de) {
         filter();
        }

        @Override
        public void removeUpdate(DocumentEvent de) {
            filter();
        }

        @Override
        public void changedUpdate(DocumentEvent de) {
            filter();
        }
        public void filter(){
             SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                comboFilter(textfield.getText());
            }});
        }           });

错误是:

  errorcom.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"

comboFilter()代码为:

The comboFilter() code is:

public void comboFilter(String enteredText) {
List<String> filterArray= new ArrayList<String>();

        String lname="";
        String fname= "";
        String mi= "";
        String id= "";

 try{
String str="SELECT * FROM patient_record WHERE firstname  LIKE '"+enteredText+"%' OR lastname  LIKE '"+enteredText+"%' OR patient_id  LIKE '"+enteredText+"%'";
Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost/patient";
    Connection con = DriverManager.getConnection(url,"root","");

 Statement stmt=con.createStatement();
 ResultSet rs=stmt.executeQuery(str);
 while(rs.next()){
  lname=rs.getString("lastname");
  fname= rs.getString("firstname");
  mi= rs.getString("middlename");
  id= rs.getString("patient_id");
  String str1 = lname+", "+fname+" "+mi+". \t"+id;
  filterArray.add(str1);
 }}
catch(Exception ex){
 System.out.println("error"+ex);   
}

if (filterArray.size() > 0) {
    jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray()));
    jComboBox1.setSelectedItem(enteredText);
    jComboBox1.showPopup();
}
else {
    jComboBox1.hidePopup();
} 
}

我知道我的解释方式很难理解.请多多包涵.你们可能会要求进一步的问题,以更好地理解我的问题.非常感谢!

I know the way I explained it is difficult to understand. Please bear with me. You guys may ask for further questions to better understand my question. Thanks a lot!

推荐答案

因此,我已经举了一个小例子来帮助您,但在此之前:

So I've made a small example to help you, but before that:

  1. 您的SQL错误连接过多",您很可能想在打开与数据库的连接的所有位置执行con.close(),如下所示:

 Connection con = null
 try {
     // create the connection and do your database work here
 } catch (Exception ex) {
     // log your exception here
 } finally {
     if (con != null) {
         // finally lets close the connection (event in the event of a exception)
         con.close();
     }
 }

  • DialogVirtualKeyboardReal代码(对作者无罪不是最好的,因为它不能很好地适应键盘不是 modal 的情况),所以您不能除非您将其设置为 modal (即将true传递到DialogVirtualKeyboardReal构造函数中(这是我的示例所做的工作),或对实际的DialogVirtualKeyboardReal进行更改),否则在输入对话框时会显示整个新话题.

  • The DialogVirtualKeyboardReal code (no offence to the author is not the best as it doesn't cater well for the scenario of the keyboard not being modal), so you cant have the dialog show while typing unless you make it modal i.e. pass true into the DialogVirtualKeyboardReal constructor (which is what my example does), or make changes to the actual DialogVirtualKeyboardReal, but thats a whole new topic.

    由于我的上述声明,在键入时显示JComboBox弹出窗口没有意义,因为它可能会覆盖键盘.

    Because of my above statement it doesnt make sense to show the JComboBox popup as you type as it potentially will cover the keyboard.

    话虽如此,我希望这可以帮助您入门(我的comboFilter方法只是模拟响应,就像它是来自数据库的结果一样):

    With all that said I hope this helps get you started (my comboFilter method simply mocks up a response as if it was a result from the database):

    TestApp.java

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    
    public class TestApp {
    
        private JComboBox<String> jComboBox1;
        private final ArrayList<String> listOfNames = new ArrayList<>();
    
        public TestApp() {
            listOfNames.add("David Kroukamp");
            listOfNames.add("Abra");
            listOfNames.add("Camickr");
            listOfNames.add("Hovercraft Full Of Eels");
            listOfNames.add("Andrew Thompson");
            listOfNames.add("MadProgrammer");
            listOfNames.add("TrashGod");
            listOfNames.add("Gilbert Le Blanc");
            listOfNames.add("mKorbel");
            listOfNames.add("kleopatra");
            listOfNames.add("Reimeus");
            listOfNames.add("StanislavL");
            listOfNames.add("Paul Samsotha");
            listOfNames.add("Guillaume Polet");
            createAndShowGui();
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(TestApp::new);
        }
    
        private void createAndShowGui() {
            JFrame frame = new JFrame("TestApp");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            jComboBox1 = new JComboBox<>(new DefaultComboBoxModel(listOfNames.toArray()));
    
            JLabel nameLabel = new JLabel("Name:");
            JTextField textField = new JTextField(20);
            textField.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    comboFilter(textField.getText());
                }
    
                @Override
                public void removeUpdate(DocumentEvent e) {
                    comboFilter(textField.getText());
                }
    
                @Override
                public void changedUpdate(DocumentEvent e) {
                    // plain text components dont fire this
                }
            });
    
            JButton showKeyboardButton = new JButton("Show Keyboard");
            showKeyboardButton.addActionListener((ActionEvent e) -> {
                new DialogVirtualKeyboardReal(frame, true, textField);
            });
    
            JPanel panel = new JPanel();
            panel.add(nameLabel);
            panel.add(textField);
            panel.add(showKeyboardButton);
    
            frame.add(panel, BorderLayout.CENTER);
            frame.add(jComboBox1, BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
    
            new DialogVirtualKeyboardReal(frame, false, textField);
        }
    
        public void comboFilter(String enteredText) {
            List<String> filterArray = new ArrayList<>();
    
            listOfNames.forEach((item) -> {
                if (item.contains(enteredText)) {
                    filterArray.add(item);
                }
            });
    
            if (filterArray.size() > 0) {
                jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray()));
                //jComboBox1.showPopup();
            } else {
                //jComboBox1.hidePopup();
            }
        }
    }
    

    这篇关于如果不是keyEvents,我应该为屏幕键盘使用什么事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆