JTextField仅显示2位小数

3

我一直在谷歌上寻找解决这个问题的方法,可能已经找到了,但我对编程的理解水平很一般。

我有一个计算过程,在两个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

        }
    }   
}

1
  1. 考虑使用带有SpinnerNumberModelJSpinner而不是文本字段。 2) 但在其他情况下,请查看DecimalFormat。 3) catch(Exception a) {} 不要忽略异常!应该是:catch(Exception a) { e.printStackTrace(); } 4) fDecorator.setSize(420, 130); 最好使用fDecorator.pack();..
- Andrew Thompson
1
  1. double Length.. 请学习常见的Java命名规范(命名约定-例如EachWordUpperCaseClassfirstWordLowerCaseMethod()firstWordLowerCaseAttribute,除非它是一个UPPER_CASE_CONSTANT),并始终保持一致。
- Andrew Thompson
4个回答

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

您需要格式化的双精度浮点数为 yourDouble。

您可以将不同的字符串传递到 DecimalFormat 构造函数中以产生不同的效果。例如,DecimalFormat("###,###,###.00") 在小数点前有最多 9 位数字的情况下,会在每个 3 个数字处添加一个逗号。


1
尝试类似以下的内容:
DecimalFormat df = new DecimalFormat("#.00");
tSize.setText(Double.toString(df.format(Length * Width)));

我尝试过这个,但它没有起作用!虽然我理解它的前提。Eclipse给了我一个错误提示,告诉我要删除toString,但我需要它。 - Starmaderp

1
导入DecimalFormat类,然后创建一个实例。接下来,在您的textfield上使用setText方法,并将十进制格式应用于您的变量:
import java.text.DecimalFormat;

double total 11.00

DecimalFormat decfor = new DecimalFormat("0.00");
txtfield.setText(String.valueOf(decfor.format(total)));

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接