如果找到的值超过最大值,则使用DocumentFilter的JTextField自动设置为最大值

时间:2017-05-03 14:07:53

标签: java swing

我已经尝试调试这几天了,这是我能找到的最接近的事情> How to set a Maximum and Minimum value that can be entered in a Jformattedtextfield , using DocumentFilter?

问题1:问题是它限制了输入而不是自动填充最大值。我不确定如何做到这一点。例如,由于maxValue设置为255,如果我输入" 256"或" 345",它被困在" 25"或" 34"而不是自动输入" 255"。

此外,如果我复制并粘贴大于" 255"在文本框中(当文本框当前没有值时),它不会键入任何值(当它应该只键入" 255")。

问题2:我还想让它执行第testObject.setObjectValue(value)行,但我不确定在哪一行输入此行。

问题1:我会查看此文件的代码(RestrictedNumberDocumentFilter.java)

问题2:我会查看此文件代码(TestGui.java)中的代码段:

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

以下是3个文件......

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

1 个答案:

答案 0 :(得分:2)

请考虑使用JSpinner,如上面提到的@Andrew Thompson所述。

要自动将文本框设置为最大值,如果键入的值已结束,您可以执行以下操作(在文档过滤器替换方法中):

  • 连接当前文本值和要插入的文本以获取文本&#34;来自替换&#34;
  • 将文本转换为整数值(处理NumberFormatException)
  • 如果值大于最大值(低于最小值),则设置值为最大值(最小值)。
  • 将您的值写入文本框

简短示例(我使用了一个简单的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 ...
        }
    }
}