简体   繁体   中英

JTextField using DocumentFilter auto set to max value if value found is over max

I've been trying to debug this for a few days now and this was the closest thing i could find > How to set a Maximum and Minimum value that can be entered in a Jformattedtextfield , using DocumentFilter?

Issue 1: The problem is it limits the input instead of auto-filling in the max value. I'm not sure how to get it to do this. For example, since the maxValue is set at 255, if I enter "256" or "345", it gets stuck at "25" or "34" instead of auto-input "255".

In addition, if i copy and paste a number greater than "255" in the text box (while the textbox currently has no value), it doesn't type any values in (when it should just type in "255").

Issue 2: I would also like to have it execute the line testObject.setObjectValue(value) , but I'm not sure where to input this line.

For Issue 1: I would look at this file's code (RestrictedNumberDocumentFilter.java)

For Issue 2: I would look at the code snippet from this file's code (TestGui.java):

private void setEnterTxtInTextFieldAction(){
    AbstractDocument doc = (AbstractDocument )enterTxtInTextField.getDocument();
    doc.setDocumentFilter(new RestrictedNumberDocumentFilter (testObject.getMinValue(), testObject.getMaxValue()));
}

Here are the 3 files...

TestObject.Java:

public class TestObject {
    private int objectValue;
    private final int maxValue = 255;
    private final int minValue = 0;

    protected int getMaxValue(){
        return this.maxValue;
    }

    protected int getMinValue(){
        return this.minValue;
    }

    protected int getObjectValue(){
        return this.objectValue;
    }

    protected void setObjectValue(int someValue){
        if (someValue > this.maxValue){
            this.objectValue = this.maxValue;
        } else if (someValue < this.minValue){
            this.objectValue = this.minValue;
        } else {
            this.objectValue = someValue;
        }
    }
}

TestGui.java:

import java.awt.*;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestGui extends JFrame {
    //**************************************************************************************
    // Variables
    private TestObject testObject = new TestObject();
    private int enterTxtInTextFieldFontSize = 16;
    private int enterTxtInTextFieldWidth = 100;
    private int enterTxtInTextFieldHeight = 40;
    private JTextField enterTxtInTextField = createWhiteBoldFgDarkGreyBgFixedSizeAlignTextField("", enterTxtInTextFieldFontSize, enterTxtInTextFieldWidth, enterTxtInTextFieldHeight, SwingConstants.LEFT);;
    private JPanel topFrame = createTopFrame();
    private JScrollPane topFrameScroll = createTopScrollPane();
    private JPanel centerFrame = createCenterFrame();

    //**************************************************************************************
    // Constructor

    TestGui(){
        add(topFrameScroll, BorderLayout.NORTH);
        add(centerFrame, BorderLayout.CENTER);

        setSize(1280,720);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //**************************************************************************************
    // Support Methods
    protected static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch(NumberFormatException e) {
            return false;
        } catch(NullPointerException e) {
            return false;
        }
        // String can be changed into an integer
        return true;
    }

    private static GridBagConstraints setGbc(int gridx, int gridy, int gridWidth, int gridHeight, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets){
        GridBagConstraints gbc = new GridBagConstraints();

        if (anchorLocation.toUpperCase().equals("NORTHWEST")){
            gbc.anchor = GridBagConstraints.NORTHWEST;
        } else if (anchorLocation.toUpperCase().equals("NORTH")){
            gbc.anchor = GridBagConstraints.NORTH;
        } else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
            gbc.anchor = GridBagConstraints.NORTHEAST;
        } else if (anchorLocation.toUpperCase().equals("WEST")){
            gbc.anchor = GridBagConstraints.WEST;
        } else if (anchorLocation.toUpperCase().equals("EAST")){
            gbc.anchor = GridBagConstraints.EAST;
        } else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
            gbc.anchor = GridBagConstraints.SOUTHWEST;
        } else if (anchorLocation.toUpperCase().equals("SOUTH")){
            gbc.anchor = GridBagConstraints.SOUTH;
        } else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
            gbc.anchor = GridBagConstraints.SOUTHEAST;
        } else {
            gbc.anchor = GridBagConstraints.CENTER;
        }

        gbc.gridx = gridx; // column
        gbc.gridy = gridy; // row
        gbc.gridwidth = gridWidth; // number of columns
        gbc.gridheight = gridHeight; // number of rows
        gbc.ipadx = ipadx; // width of object
        gbc.ipady = ipady; // height of object
        gbc.weightx = weightx; // shifts rows to side of set anchor
        gbc.weighty = weighty; // shifts columns to side of set anchor
        gbc.insets = insets; // placement inside cell
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.fill = GridBagConstraints.VERTICAL;

        return gbc;
    }

    private Insets setInsets(int top, int left, int bottom, int right){
        Insets insets = new Insets(top,left,bottom,right);
        return insets;
    }

    //**************************************************************************************
    // Interactive Object Methods
    private JTextField createWhiteBoldFgDarkGreyBgFixedSizeAlignTextField(String text, int textSize, int width, int height, int hAlign){
        JTextField txtField = new JTextField(text);

        txtField.setForeground(Color.WHITE);
        txtField.setBackground(new Color(50,50,50));
        txtField.setCaretColor(Color.CYAN);
        txtField.setFont(new Font(text, Font.BOLD, textSize));
        txtField.setPreferredSize(new Dimension(width, height));
        txtField.setHorizontalAlignment(hAlign);
        return txtField;
    }
    //**************************************************************************************
    // Object Action Methods
    private void setEnterTxtInTextFieldAction(){
        AbstractDocument doc = (AbstractDocument )enterTxtInTextField.getDocument();
        doc.setDocumentFilter(new RestrictedNumberDocumentFilter (testObject.getMinValue(), testObject.getMaxValue()));
    }

    //**************************************************************************************
    // Panel Methods

    private JPanel createTopFrame(){
        // pnl.add(object, setGbc(column,row, columnFill,rowFill, columnExtraWidth,columnExtraWidth, cellAlignment, weightColumn, weightRow, setInsets(top, left, bottom, right)));

        JPanel pnl = new JPanel();

        pnl.setLayout(new GridBagLayout());

        Border gridBorder = BorderFactory.createMatteBorder(4,4,4,4,Color.BLUE);

        JLabel enterText = new JLabel("Enter Text");
        enterText.setBorder(gridBorder);
        enterTxtInTextField.setBorder(gridBorder);
        setEnterTxtInTextFieldAction();
        pnl.add(enterText, setGbc(0,0, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));
        pnl.add(enterTxtInTextField, setGbc(0,1, 1,1, 0,0, "CENTER", 0, 0, setInsets(10, 10, 10, 10)));

        return pnl;
    }

    private JScrollPane createTopScrollPane(){
        JScrollPane scrollPane = new JScrollPane();
        Border raisedBevel = BorderFactory.createRaisedBevelBorder();
        Border lineBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, new Color(224,224,224));
        Border loweredBevel = BorderFactory.createLoweredBevelBorder();
        Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
        Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);

        scrollPane.setBorder(compoundFinal);
        scrollPane.getViewport().setView(topFrame);
        return scrollPane;
    }

    private JPanel createCenterFrame() {
        JPanel pnl = new JPanel();
        Border raisedBevel = BorderFactory.createRaisedBevelBorder();
        Color lineColor = new Color(224, 224, 224);
        Border lineBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, lineColor);
        Border loweredBevel = BorderFactory.createLoweredBevelBorder();
        Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
        Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
        TitledBorder topFrameTitle = BorderFactory.createTitledBorder(compoundFinal, "Stuff");
        topFrameTitle.setTitleJustification(TitledBorder.CENTER);

        pnl.setBorder(topFrameTitle);

        return pnl;
    }

    //**************************************************************************************

    public static void main(String[] args) {

        new TestGui();
    }
}

RestrictedNumberDocumentFilter.java:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class RestrictedNumberDocumentFilter extends DocumentFilter{

    private int min;
    private int max;

    public RestrictedNumberDocumentFilter(int min, int max){
        if ( max < min ){
            int temp = max;
            max = min;
            min = temp;
        }
        this.min = min;
        this.max = max;
    }

    @Override
    public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) throws BadLocationException {
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        if ( test(sb.toString()) ){
            fb.insertString(off, str, attr);
        } else {
            //warn
        }

    }
    @Override
    public void replace(DocumentFilter.FilterBypass fb, int off, int len, String str, AttributeSet attr)throws BadLocationException {
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(off, off+len, str);
        if ( test(sb.toString()) ){
            fb.replace(off, len, str, attr);
        } else {
            //warn
        }

    }
    /**
     * Sanitized the input
     * @param val
     * @return
     */
    private boolean test(String val){
        try{
            double d = Double.parseDouble(val);
            if ( d >= min && d <= max ){
                return true;
            }
            return false;
        }catch(NumberFormatException e){
            return false;
        }
    }
}

Please consider using a JSpinner, as @Andrew Thompson suggested above.

To automatically set the text box to the maximum value, if typed value is over, you may do the following (in your Document Filter replace method) :

  • Concatenate current text value and text to insert to get the text "resulting from replacement"
  • Convert text to an integer value (handling NumberFormatException)
  • If value is greater than maximum (lower than minimum) set value to maximum (minimum).
  • Write your value to the text box

Short example (i used a simple JTextField):

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
public class Test
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            public void run () {
                createAndShowGUI ();
            }
        });
    }
    private static void createAndShowGUI () {
        // Creating JTextField
        JTextField textField = new JTextField (5);
        ((AbstractDocument) textField.getDocument ()).setDocumentFilter (new CustomDocumentFilter ());
        // Creating example frame
        JFrame frame = new JFrame ("Test");
        JPanel contentPane = new JPanel (new FlowLayout (FlowLayout.CENTER, 75, 50));
        contentPane.add (textField);
        frame.setContentPane (contentPane);
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.pack ();
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);
    }
}
class CustomDocumentFilter extends DocumentFilter
{
    @Override public void replace (FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        String textAfterReplacement = new StringBuilder (fb.getDocument ().getText (0, fb.getDocument ().getLength ())).replace (offset, offset + length, text).toString ();
        try {
            int value = Integer.parseInt (textAfterReplacement);
            if (value < 0) value = 0;
            else if (value > 255) value = 255;
            super.replace (fb, 0, fb.getDocument ().getLength (), String.valueOf (value), attrs);
        }
        catch (NumberFormatException e) {
            // Handle exception ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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