JTextField只显示2个小数位

时间:2015-03-08 16:47:47

标签: java swing double decimal jtextfield

我一直在谷歌搜索解决这个问题的方法,我可能已经找到了,但我对编程很陌生,所以我的理解水平充其量只是平庸。

我在两个JTextField个对象中进行计算,将两个输入值相乘,并将第三个文本字段的文本设置为答案。进行十进制计算时,我希望它只显示两位小数。

我添加了整个代码而不是摘要。

以下是代码:

    public class Decorator implements ActionListener
    {
        JFrame fDecorator; // Declare Decorator frame
        JLabel lSize, lType, lTotal, lPrice, lx, lEquals; // Declare Labels
        JTextField tLength, tWidth, tSize, tTotal; // Declare JTextFields
        JComboBox<String> cbFlooring; //Declare JComboBox
        JButton bCalculate1, bCalculate2, bHelp; // Declare JButtons
        static double priceTotal, floorPrice, floorSize; // Declare double variables

    Decorator()
    {       
        String[] type_floor = new String[] // Create an array called Type_Floor
        {" Select ","Wood £0.24", "Ceramic £0.37", "Stone £0.86", "Lino £1.24", "Marble £1.76",
        "Laminate £2.10", "Bamboo £2.34", "Carpet £3.78"}; // Add array names for JComboBox

        fDecorator = new JFrame("Flooring Decorator"); // Add the Frame
        fDecorator.setResizable(false); // Disallow user resizing of frame
        fDecorator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        lSize = new JLabel("Input Size of your room (Meters): "); // Add size of floor Label
        lType = new JLabel("Type of flooring: "); // Add type of flooring Label
        lTotal = new JLabel("Total Price = "); // Add Total price of flooring Label
        lx = new JLabel("x"); // Add x Label
        lEquals = new JLabel("="); // Add equals Label
        lPrice = new JLabel ("Price of floor per square Meter"); // Adds Price Label

        bCalculate1 = new JButton("Calculate"); // Add calculate Button
        bCalculate2 = new JButton("Calculate"); // Add calculate Button
        bHelp = new JButton("Help"); // Add Help Button

        tLength = new JTextField(5); // Add user editable Text Field
        tWidth = new JTextField(5); // Add second user editable Text Field
        tSize = new JTextField(5); // Add total size of room Text Field
        tTotal = new JTextField(5); // Add total price Text Field

        tTotal.setEditable(false); // Disallow editing of tTotal
        tSize.setEditable(false); // Disallow editing of tSize

        cbFlooring = new JComboBox<>(type_floor); // Add ComboBox, and type cast Array

        fDecorator.setLayout(new FlowLayout()); // Set the layout of Decorator to FlowLayout

        fDecorator.add(lSize); // Add Size Label
        fDecorator.add(tLength); // Add Entry1 TextField
        fDecorator.add(lx); // Add x Label
        fDecorator.add(tWidth); // Add Entry2 TextField
        fDecorator.add(lEquals); // Add Equals Label
        fDecorator.add(tSize); // Add Size TextField
        fDecorator.add(bCalculate1); // Add Calculator1 Button
        fDecorator.add(lPrice); // Add Price Label
        fDecorator.add(cbFlooring); // Add Flooring ComboBox    
        fDecorator.add(bCalculate2); // Add Calculator2 Button
        fDecorator.add(lTotal); // Add Total Label
        fDecorator.add(tTotal); // Add Total TextField
        fDecorator.add(bHelp); // Add Help Button

        bCalculate1.addActionListener(this); // Adds an action listener to Calculate button
        bCalculate2.addActionListener(this); // Adds an action listener to Calculate2 button
        bHelp.addActionListener(this); // Adds an action listener to Help button
        cbFlooring.addActionListener(this); // Adds action listener to ComboBox

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        fDecorator.setLocation(dim.width/3-fDecorator.getSize().width/3, dim.height/3-fDecorator.getSize().height/3);

        fDecorator.setSize(420, 130); // Set frame size too 400 by 200
        fDecorator.setVisible(true); // Set frame to visible

    }


    @Override
    public void actionPerformed(ActionEvent e) // Action Listener
    {

        try // Handle exceptions with code inside this block
        {
             JComboBox<String> selectionBox = (JComboBox<String>) e.getSource(); // Declare parameterised ComboBox selectionBox
             String selectedFloor = (String) selectionBox.getSelectedItem(); // Declare selectedFloor as string inside ComboBox

             if(selectedFloor.equals("Wood £0.24")) // If selected Equals Wood
                 floorPrice = 0.24;  // Assign floorPrice value 0.24         

             else if(selectedFloor.equals("Ceramic £0.37")) // If selected Equals Ceramic
                 floorPrice = 0.37;  // Assign floorPrice value 0.37

             else if(selectedFloor.equals("Stone £0.86")) // If selected Equals Stone
                 floorPrice = 0.86;  // Assign floorPrice value 0.86

             else if(selectedFloor.equals("Lino £1.24")) // If selected Equals Lino
                 floorPrice = 1.24;  // Assign floorPrice value 1.24

             else if(selectedFloor.equals("Marble £1.76")) // If selected Equals Marble
                 floorPrice = 1.76;  // Assign floorPrice value 1.76

             else if(selectedFloor.equals("Laminate £2.10")) // If selected Equals Laminate
                 floorPrice = 2.10;  // Assign floorPrice value 2.10

             else if(selectedFloor.equals("Bamboo £2.34")) // If selected Equals Bamboo
                 floorPrice = 2.34;  // Assign floorPrice value 2.34

             else if(selectedFloor.equals("Carpet £3.78")) // If selected Equals Carpet
                 floorPrice = 3.78; // Assign floorPrice value 3.78
        }

        catch(Exception a) // Handle exception using this
        {
            // Does nothing if an exception is encountered, prevents program from crashing and handles exception
        }

        try // Handle exception with code inside this block
        {
            char[] len1 = tLength.getText().toCharArray(); // Declares a char variable that gets the text from tEntry1
            char[] len2 = tWidth.getText().toCharArray(); // Declares a char variable that gets the text from tEntry2

            for(int loop1 = 0; loop1 < len1.length; loop1++) // For loop that searches through the TextFields
            {
                if(len1[loop1] == '-' || len2[loop1] == '-') // If the loop finds a - sign
                    JOptionPane.showMessageDialog(null,"No Negative numbers please!"); // Displays an error message
            }

            if (tLength.getText() != null && tWidth.getText() != null) // if TextFields have inputs
            {
                double length = Double.parseDouble(tLength.getText()); // Gets string from TextField and converts to double
                double width = Double.parseDouble(tWidth.getText()); // Gets string from TextField and converts to double

                if(e.getSource() == bCalculate1) // When Calculate button is clicked
                {
                    tSize.setText(Double.toString(length * width)); // Times input 1 and 2 to find surface area
                }
            }
        }

        catch(Exception ab) // Handle exception using this
        {
            JOptionPane.showMessageDialog(null,"No Text Please!");// Does nothing if an exception is encountered, prevents program from crashing
        }   

        try // Handle exception with code inside this block
        {
            if(e.getSource() == bCalculate2) // If Calculate2 button is pressed
            {
                floorSize = Double.parseDouble(tSize.getText()); // Get text value from tSize and assign value too floorSize
                priceTotal = floorPrice * floorSize; // Assign value to priceTotal              
                tTotal.setText(""+priceTotal); // Set tTotal TextField
            }
        }

        catch(Exception abc) // Handle exceptions using this
        {
            System.out.println("Exception occured!!!!");// If an exception is encountered, prevents program from crashing and handles exception
        }

        if(e.getSource() == bHelp)
        {
            JFrame fHelp = new JFrame("Help Screen"); // Declare JFrame fHelp
            JLabel lWelcomeHelp = new JLabel("<html>Welcome to the help screen!<br> This screen will guide you though using my decorator application!<br> Firslty input the length and width into the text fields, then press calculate.<br> This will generate the size of the floor you're going to be decorating.<br>After that select which floor you would like to use,<br>the price for each type of flooring is displayed next to it.<br> After deciding on a floor press the second calculate button to price up your new floor!<html>", SwingConstants.CENTER);
            // Declare JLabel WelcomeHelp

            fHelp.setLayout(new FlowLayout()); // Set fHelp frame layout as FlowLayout

            fHelp.add(lWelcomeHelp); // Add WelcomeHelp JLabel to fHelp frame

            fHelp.setSize(600, 250); // Set size of frame
            fHelp.setVisible(true); // Make frame visible

        }
    }   
}

3 个答案:

答案 0 :(得分:2)

DecimalFormat dc = new DecimalFormat("0.00");
String formattedText = dc.format(yourDouble);

你的文件是想要格式化的双倍。

您可以将不同的字符串传递给DecimalFormat构造函数以获得不同的效果。例如,DecimalFormat("###,###,###.00")会在每3个数字处放置一个逗号,其中要格式化的数字最多为小数点前9位数。

答案 1 :(得分:1)

尝试类似:

DecimalFormat df = new DecimalFormat("#.00");
tSize.setText(Double.toString(df.format(Length * Width)));

答案 2 :(得分:-1)

double length = Double.parseDouble(tLength.getText());
double width = Double.parseDouble(tWidth.getText());

int numberOfDigitsAfterDecimal = 2;
Double yourDoubleResult = length * width;
Double resultToBeShown = new BigDecimal(yourDoubleResult).setScale(numberOfDigitsAfterDecimal, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(resultToBeShown.toString());

 if(e.getSource() == bCalculate) {
      tSize.setText(resultToBeShown.toString());
 }