MaskFormatter makes Components Sporadically Appear In Panel

49 Views Asked by At

I'm trying to make the GUI for a program that solved quadratic equations.

I'm using JFormattedTextfields to restrict user entry to numbers, and to do this I'm using MaskFormatter. Problem is, this causes the components to fluctuate between appearing correctly in the panel, partly appearing, and then not appearing at all.

I've figured out that the problem has something to do with MaskFormatter, because when I call the constructor that takes no arguments for JFormattedTextFields, everything appears correctly.

This is my code:

public JPanel createEquationPanel(int w, int h) throws ParseException {
    equationPanel = new JPanel(new GridBagLayout());
    equationPanel.setSize(w,h);
    equationPanel.setBorder(BorderFactory.createTitledBorder("Quadratic Equation"));
    equationPanel.setBackground(Color.WHITE);

    aLabel = createLabel("a =", "Enter the \'a\' value for the equation", Font.ITALIC, 25.0f);
    bLabel = createLabel("b =", "Enter the \'b\' value for the equation", Font.ITALIC, 25.0f);
    cLabel = createLabel("c =", "Enter the \'c\' value for the equation", Font.ITALIC, 25.0f);
    equation = createLabel("", "The equation", Font.PLAIN, 35.0f);

    a = createFormattedTextField();
    b = createFormattedTextField();
    c = createFormattedTextField();

    equationPanel.add(aLabel,setGbc(0,0,0.1,0.1));
    equationPanel.add(a,setGbc(1,0,0.1,0.1));
    equationPanel.add(bLabel,setGbc(2,0,0.1,0.1));
    equationPanel.add(b,setGbc(3,0,0.1,0.1));
    equationPanel.add(cLabel,setGbc(4,0,0.1,0.1));
    equationPanel.add(c,setGbc(5,0,0.1,0.1));

    equationPanel.add(equation,    setGbc(2,2,GridBagConstraints.FIRST_LINE_START,5,0.3,0.3));

    return equationPanel;
}

Method that creates the FormattedTextFields

private JFormattedTextField createFormattedTextField() {
    JFormattedTextField tf = new JFormattedTextField(createFormatter("######"));
    tf.setColumns(5);

    return tf;
} 

private MaskFormatter createFormatter(String s) {
    MaskFormatter mask = null;

    try {
        mask = new MaskFormatter(s);
    } catch (ParseException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error occurred", "Error", JOptionPane.ERROR_MESSAGE);
    }

    return mask;
}

Also, I specify a size for the panel (w:495,h:250), and I noticed that even if the JLabels and JFormattedTextfields don't appear initially, when I resize the actual frame they do appear. So in short, they are always there, they just don't always appear in the panel size I specify.

0

There are 0 best solutions below