how to make cursor can enter jtextfield but the only way to give it a text is click a button?

前端 未结 2 751
旧巷少年郎
旧巷少年郎 2021-01-14 16:24

i have jTextfield and jButton..

how to

  • user can click on jTextfield(mouse can enter/exited on jtextfield), but if user typing something it will not do
相关标签:
2条回答
  • 2021-01-14 16:52

    in the key listener of the jTextfield, in the keyTyped event, check the e.getKeyChar() if it is the backspace, if not, do e.consume(); it will cancel the event

    the keychar for backspace is 8

    here is an example:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    
    
    public class ConsumeExceptForBackSpace extends JFrame {
    
        private boolean canWrite = false;
    
        public ConsumeExceptForBackSpace() {
            super();
    
            JButton b = new JButton("Click");
            JTextField f = new JTextField("");
            this.setLayout(new BorderLayout());
            this.add(b, BorderLayout.CENTER);
            this.add(f, BorderLayout.SOUTH);
    
            b.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    canWrite = !canWrite;
                }
            });
    
            f.addKeyListener(new KeyListener() {
    
                @Override
                public void keyTyped(KeyEvent e) {
                    if(e.getKeyChar() != KekEvent.VK_BACK_SPACE && !canWrite) e.consume();
                }
    
                @Override
                public void keyReleased(KeyEvent e) {
    
                }
    
                @Override
                public void keyPressed(KeyEvent e) {
    
                }
            });
    
            this.pack();
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setVisible(true);
        }
    
        public static void main(String[] args) {
            new ConsumeExceptForBackSpace();
        }
    }
    
    0 讨论(0)
  • 2021-01-14 17:08

    Use a DocumentFilter, simply add it to your JTextField like so:

     public class Test {
    
        public void initComponents() {
    
            //create frame
    
            //add DoucmentFilter to JTextField
            MyDocumentFilter myFilter = new MyDocumentFilter();
            JTextField myArea = new JTextField();
            ((AbstractDocument)myArea.getDocument()).setDocumentFilter(myFilter);
    
             //add components set frame visible
        }
    
     }
    
    class MyDocumentFilter extends DocumentFilter {
    
        @Override
        public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
            super.replace(fb, i, i1, string, as);
        }
    
        @Override
        public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
            super.remove(fb, i, i1);
        }
    
        @Override
        public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
            super.insertString(fb, i, string, as);
        }
    
    }
    

    alternatively

    You may want to create a custom JTextField which already has a DocumentFilter (for re-usability) something like:

    public class MyCustomField extends JTextField {
    
        public MyCustomField(int cols) {
            super(cols);
        }
    
        protected Document createDefaultModel() {
            return ((Document) new MyDocument());
        }
    
        static class MyDocument extends DocumentFilter {
    
            @Override
            public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
                super.insertString(fb, i, string, as);
            }
    
            @Override
            public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
                super.remove(fb, i, i1);
            }
    
            @Override
            public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
                super.replace(fb, i, i1, string, as);
            }
        }
    }
    

    Edit from Hovercraft
    I was thinking more along these lines

    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class Test {
    
       public void initComponents() {
    
          JPanel panel = new JPanel();
          final MyDocumentFilter myFilter = new MyDocumentFilter();
          final JTextField myArea = new JTextField(20);
          ((AbstractDocument) myArea.getDocument()).setDocumentFilter(myFilter);
    
          panel.add(myArea);
    
          panel.add(new JButton(new AbstractAction("Set Text") {
    
             @Override
             public void actionPerformed(ActionEvent arg0) {
                myFilter.setFiltering(false);
                myArea.setText("Fe Fi Fo Fum");
                myFilter.setFiltering(true);
             }
          }));
    
          JOptionPane.showMessageDialog(null, panel);
    
          // add components set frame visible
       }
    
       public static void main(String[] args) {
          new Test().initComponents();
       }
    
    }
    
    class MyDocumentFilter extends DocumentFilter {
       private boolean filtering = true;
    
       @Override
       public void replace(FilterBypass fb, int i, int i1, String string,
             AttributeSet as) throws BadLocationException {
          if (!filtering) {
             super.replace(fb, i, i1, string, as);
          }
       }
    
       @Override
       public void remove(FilterBypass fb, int i, int i1)
             throws BadLocationException {
          int offset = 0;
          int length = fb.getDocument().getLength();
          super.remove(fb, offset, length);
       }
    
       @Override
       public void insertString(FilterBypass fb, int i, String string,
             AttributeSet as) throws BadLocationException {
          if (!filtering) {
             super.insertString(fb, i, string, as);         
          }
       }
    
       public void setFiltering(boolean filtering) {
          this.filtering = filtering;
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题