简体   繁体   English

在jTextfield中键入值后,是否有可能在不使用jButton的情况下自动按下?

[英]Is it possible that after typing a value in jTextfield it will automatically press without using jButton?

Is it possible that after typing a value in jTextfield it will automatically press without using jButton? 在jTextfield中键入值后,是否有可能在不使用jButton的情况下自动按下? i dont know if its possible.. well ill be using it in my barcode scanner after the scan and display the values the jTextfield will automatically receive and start the query on database 我不知道它是否可能..扫描后是否会在条形码扫描器中使用它并显示jTextfield会自动接收并在数据库上开始查询的值

The answer depends on your definition of "press". 答案取决于您对“新闻”的定义。 In my experience, the expectations are, when the barcode is scanned, the action will be performed without the user having to do anything extra 根据我的经验,期望的是,在扫描条形码时,无需用户做任何额外的操作即可执行操作

Based on that assumption, you have two basic choices 基于此假设,您有两个基本选择

Fixed length 固定长度

If you know the length of the bar code (and it's constant), you could use a DocumentFilter to detect when the length is reached and trigger a action 如果您知道条形码的长度(并且它是恒定的),则可以使用DocumentFilter检测何时达到该长度并触发操作

public class BarCodeLengthDocumentListener implements DocumentListener {

    private ActionListener actionListener;
    private int barCodeLength;

    public BarCodeLengthDocumentListener(int barCodeLength, ActionListener actionListener) {
        this.actionListener = actionListener;
        this.barCodeLength = barCodeLength;
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        doCheck(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        doCheck(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doCheck(e);
    }

    protected void doCheck(DocumentEvent e) {
        Document doc = e.getDocument();
        if (doc.getLength() >= barCodeLength) {
            try {
                String text = doc.getText(0, doc.getLength());
                ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, text);
                actionListener.actionPerformed(evt);
            } catch (BadLocationException exp) {
                exp.printStackTrace();
                ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null);
                actionListener.actionPerformed(evt);
            }
        }
    }

}

So, basically, this allows you to specify the expected length of the bar code and when it's reached, it will trigger the ActionListener , passing the text through the ActionEvent 因此,基本上,这使您可以指定条形码的预期长度,当条形码达到预期长度时,它将触发ActionListener ,将文本传递给ActionEvent

Delayed Action 延迟行动

If you don't know the length (or it's variable), another option is to inject some kind of delay between when a document event occurs and when you trigger the ActionListener 如果您不知道长度(或它的变量),另一种选择是在文档事件发生与触发ActionListener之间注入某种延迟

public class DelayedDocumentListener implements DocumentListener {

    private ActionListener actionListener;
    private String text;
    private Timer timer;

    public DelayedDocumentListener(ActionListener actionListener) {
        this.actionListener = actionListener;
        timer = new Timer(1000, new ActionListener() {
                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, text);
                                            actionListener.actionPerformed(evt);
                                        }
                                    });
        timer.setRepeats(false);
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        doCheck(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        doCheck(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doCheck(e);
    }

    protected void doCheck(DocumentEvent e) {
        try {
            Document doc = e.getDocument();
            text = doc.getText(0, doc.getLength());
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
        timer.restart();
    }

}

So this uses a Swing Timer which generates a delay (in this case of 1 second) between when a document event occurs and when it will trigger the ActionListener , each new document event interrupts the Timer , causing it to restart. 因此,这使用了Swing Timer ,该Timer在文档事件发生与触发ActionListener之间产生延迟(在这种情况下为1秒),每个新文档事件都会中断Timer ,从而导致重新启动。 This means that there must be at least 1 second between the last document event and the triggering of the ActionListener . 这意味着在最后一个文档事件与ActionListener的触发之间必须至少有1秒的时间。

Because sometimes people need to enter the barcode manually, you might want to play with that delay. 由于有时人们需要手动输入条形码,因此您可能需要延迟播放。

Runnable example... 可运行的示例...

So, this basically presents both ideas, it uses a java.awt.Robot to inject key strokes into the keyboard buffer which should simulate most barcode scanners 因此,这基本上提出了两种想法,它使用java.awt.Robot将击键注入键盘缓冲区,该缓冲区应该模拟大多数条形码扫描仪

import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            BarCodeLengthDocumentListener lengthListener = new BarCodeLengthDocumentListener(7, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String text = e.getActionCommand();
                    JOptionPane.showMessageDialog(TestPane.this, text);
                }
            });
            DelayedDocumentListener delayedListener = new DelayedDocumentListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String text = e.getActionCommand();
                    JOptionPane.showMessageDialog(TestPane.this, text);
                }
            });

            JTextField field1 = new JTextField(7);
            field1.getDocument().addDocumentListener(lengthListener);
            JTextField field2 = new JTextField(7);
            field2.getDocument().addDocumentListener(delayedListener);

            add(field1);
            add(field2);

            JButton simLength = new JButton("Simulate Length");
            simLength.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    field1.setText(null);
                    field1.requestFocusInWindow();
                    Thread t = new Thread(new Simulator());
                    t.start();
                }
            });
            JButton simDelay = new JButton("Simulate Delay");
            simDelay.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    field2.setText(null);
                    field2.requestFocusInWindow();
                    Thread t = new Thread(new Simulator());
                    t.start();
                }
            });

            add(simLength);
            add(simDelay);
        }

    }

    public class Simulator implements Runnable {

        @Override
        public void run() {
            try {
                Robot bot = new Robot();
                type(KeyEvent.VK_1, bot);
                type(KeyEvent.VK_2, bot);
                type(KeyEvent.VK_3, bot);
                type(KeyEvent.VK_4, bot);
                type(KeyEvent.VK_5, bot);
                type(KeyEvent.VK_6, bot);
                type(KeyEvent.VK_7, bot);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        }

        protected void type(int keyStoke, Robot bot) {
            bot.keyPress(keyStoke);
            bot.keyRelease(keyStoke);
        }

    }

    public class BarCodeLengthDocumentListener implements DocumentListener {

        private ActionListener actionListener;
        private int barCodeLength;

        public BarCodeLengthDocumentListener(int barCodeLength, ActionListener actionListener) {
            this.actionListener = actionListener;
            this.barCodeLength = barCodeLength;
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            doCheck(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            doCheck(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            doCheck(e);
        }

        protected void doCheck(DocumentEvent e) {
            Document doc = e.getDocument();
            if (doc.getLength() >= barCodeLength) {
                try {
                    String text = doc.getText(0, doc.getLength());
                    ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, text);
                    actionListener.actionPerformed(evt);
                } catch (BadLocationException exp) {
                    exp.printStackTrace();
                    ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null);
                    actionListener.actionPerformed(evt);
                }
            }
        }

    }

    public class DelayedDocumentListener implements DocumentListener {

        private ActionListener actionListener;
        private String text;
        private Timer timer;

        public DelayedDocumentListener(ActionListener actionListener) {
            this.actionListener = actionListener;
            timer = new Timer(1000, new ActionListener() {
                                            @Override
                                            public void actionPerformed(ActionEvent e) {
                                                ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, text);
                                                actionListener.actionPerformed(evt);
                                            }
                                        });
            timer.setRepeats(false);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            doCheck(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            doCheck(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            doCheck(e);
        }

        protected void doCheck(DocumentEvent e) {
            try {
                Document doc = e.getDocument();
                text = doc.getText(0, doc.getLength());
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }
            timer.restart();
        }

    }
}

Is it possible that after typing a value in jTextfield it will automatically press without using jButton? 在jTextfield中键入值后,是否有可能在不使用jButton的情况下自动按下?

You can add an ActionListener to the text field. 您可以将ActionListener添加到文本字段。

The listener will be invoked when the text field has focus and the Enter key is pressed. 当文本字段具有焦点并按下Enter键时,将调用侦听器。

Add a KeyListener after initializing the textfield: 在初始化文本字段后添加KeyListener:

textfield.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
        System.out.println("typed: "+e.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("released: "+e.getKeyChar());
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("pressed: "+e.getKeyChar());
    }
});

and modify as needed 并根据需要进行修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM