View Javadoc

1   /**
2    * Copyright 2009 Timothy Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
3    * file except in compliance with the License. You may obtain a copy of the License at
4    * 
5    * http://www.apache.org/licenses/LICENSE-2.0
6    * 
7    * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
8    * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
9    * specific language governing permissions and limitations under the License.
10   */
11  package com.timjohnstondev.unitconverter.logic;
12  
13  import java.math.BigDecimal;
14  import java.math.MathContext;
15  import java.math.RoundingMode;
16  import java.util.ResourceBundle;
17  import javax.swing.JButton;
18  import javax.swing.JTextField;
19  
20  /**
21   * Utility class that contains all of the logic for dealing with the mole to mass calculations for the conversions.
22   */
23  public final class MolarMassLogic
24  {
25    private static final ResourceBundle RESOURCES = ResourceBundle
26        .getBundle("com.timjohnstondev.unitconverter.view.View");
27  
28    private MolarMassLogic()
29    {}
30  
31    /**
32     * Performs calculation to determine the molecular weight correction factor.
33     * 
34     * @param massMoleField massMoleField
35     * @param mass2Mole mass2Mole
36     * @param selectedButton selectedButton
37     * @param isMolUnitDivisor isMolUnitDivisor
38     * 
39     * @return the molecular weight correction factor
40     */
41    public static BigDecimal getMolecularWeightCorrection(final JTextField massMoleField, final JButton mass2Mole,
42        final Object selectedButton, final boolean isMolUnitDivisor)
43    {
44      BigDecimal mwc = BigDecimal.ONE;
45      if (massMoleField.isVisible() && massMoleField.getText() != null && !massMoleField.getText().equals("")
46          && selectedButton != null)
47      {
48        final boolean isMassToMoleConversion = isMassToMoleConversion(mass2Mole, selectedButton);
49        mwc = new BigDecimal(massMoleField.getText());
50        if ((isMassToMoleConversion && !isMolUnitDivisor) || (!isMassToMoleConversion && isMolUnitDivisor))
51        {
52          final String numberLengthLimit = RESOURCES.getString("CalculationPanel.numberLengthLimit");
53          final MathContext mathContext = new MathContext(Integer.parseInt(numberLengthLimit), RoundingMode.HALF_UP);
54          mwc = BigDecimal.ONE.divide(mwc, mathContext);
55        }
56      }
57      return mwc;
58    }
59  
60    private static boolean isMassToMoleConversion(final JButton mass2Mole, final Object selectedButton)
61    {
62      boolean isMass2Mole = false;
63      if (mass2Mole == selectedButton)
64      {
65        isMass2Mole = true;
66      }
67      return isMass2Mole;
68    }
69  }