我试图为解决二次方程的程序制作GUI。
我使用JFormattedTextfields
限制用户输入数字,为此我使用MaskFormatter
。问题是,这会导致组件在面板中正确显示之间波动,部分显示,然后根本不显示。
我已经发现问题与MaskFormatter
有关,因为当我调用不带JFormattedTextFields
参数的构造函数时,一切都会正确显示。
这是我的代码:
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;
}
创建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;
}
另外,我指定面板的大小(w:495,h:250),我注意到,即使JLabels
和JFormattedTextfields
最初没有出现,调整他们做出现的实际框架的大小。简而言之,它们总是在那里,它们并不总是出现在我指定的面板尺寸中。