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

女生的网名这么多〃 提交于 2019-12-19 09:25:07

问题


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 anything (except backspace that will remove entire text)
  • when user click the button, it will

jTextfield.setText("something");

so the only way to give jtextfield text is click the button

  • when there are a text in there (when cursor inside jtextfield) then user typing a backspace, it will remove entire text on jtextfield..

how to do this?

forgive my english.. thanks a lot for any kind of help..


回答1:


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

}



回答2:


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


来源:https://stackoverflow.com/questions/13517057/how-to-make-cursor-can-enter-jtextfield-but-the-only-way-to-give-it-a-text-is-cl

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