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

痴心易碎 提交于 2019-12-12 07:01:53

问题


Is it possible that after typing a value in jTextfield it will automatically press without using 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


回答1:


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

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

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

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. This means that there must be at least 1 second between the last document event and the triggering of the ActionListener.

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

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();
        }

    }
}



回答2:


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

You can add an ActionListener to the text field.

The listener will be invoked when the text field has focus and the Enter key is pressed.




回答3:


Add a KeyListener after initializing the textfield:

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



来源:https://stackoverflow.com/questions/42874743/is-it-possible-that-after-typing-a-value-in-jtextfield-it-will-automatically-pre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!