Java JTextField仅显示2位小数

Java JTextField仅显示2位小数,java,swing,double,decimal,jtextfield,Java,Swing,Double,Decimal,Jtextfield,我一直在用谷歌搜索这个问题的解决方案,我可能找到了,但我对编程非常陌生,所以我的理解水平充其量只是平庸 我在两个JTextField对象中进行计算,将输入值相乘,并将第三个文本字段的文本设置为答案。当进行十进制计算时,我希望它只显示两位小数 我添加了整个代码,而不是摘要 代码如下: public class Decorator implements ActionListener { JFrame fDecorator; // Declare Decorator f

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

我在两个
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

        }
    }   
}
公共类装饰器实现ActionListener
{
JFrame fDecorator;//声明装饰器框架
JLabel lSize、lType、lTotal、lPrice、lx、lEquals;//声明标签
jtextfieldtlength,tWidth,tSize,ttottal;//声明JTextFields
JComboBox;//声明JComboBox
JButton bCalculate1,bCalculate2,bHelp;//声明JButton
静态double priceTotal、floorPrice、floorSize;//声明双变量
装饰师()
{       
String[]type\u floor=new String[]//创建一个名为type\u floor的数组
{“精选”、“木材0.24英镑”、“陶瓷0.37英镑”、“石材0.86英镑”、“利诺1.24英镑”、“大理石1.76英镑”,
“层压2.10英镑”、“竹子2.34英镑”、“地毯3.78英镑”};//为JComboBox添加数组名称
fDecorator=newjframe(“地板装饰器”);//添加框架
fDecorator.setResizeable(false);//不允许用户调整帧大小
fDecorator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lSize=new JLabel(“输入房间大小(米):”;//添加地板标签的大小
lType=新的JLabel(“地板类型:”;//添加地板类型标签
lTotal=new JLabel(“Total Price=”);//添加地板标签的总价
lx=newjlabel(“x”);//添加x标签
lEquals=newjlabel(“=”;//添加等于标签
lPrice=new JLabel(“每平方米地板的价格”);//添加价格标签
bCalculate1=newjbutton(“计算”);//添加计算按钮
bCalculate2=newjbutton(“计算”);//添加计算按钮
bHelp=newjbbutton(“Help”);//添加帮助按钮
t长度=新的JTextField(5);//添加用户可编辑的文本字段
tWidth=newjtextfield(5);//添加第二个用户可编辑的文本字段
tSize=newjtextfield(5);//添加文件室文本字段的总大小
tTotal=新的JTextField(5);//添加总价文本字段
tTotal.setEditable(false);//不允许编辑tTotal
tSize.setEditable(false);//不允许编辑tSize
cbflooding=newjcombobox(type_floor);//添加组合框,然后键入cast数组
fDecorator.setLayout(new FlowLayout());//将装饰器的布局设置为FlowLayout
fDecorator.add(lSize);//添加尺寸标签
fDecorator.add(tLength);//添加Entry1文本字段
fDecorator.add(lx);//添加x标签
fDecorator.add(tWidth);//添加Entry2文本字段
fDecorator.add(lEquals);//添加等于标签
fDecorator.add(tSize);//添加大小文本字段
fDecorator.add(bCalculate1);//添加计算器1按钮
fDecorator.add(lPrice);//添加价格标签
fDecorator.add(cbflooding);//添加地板组合框
fDecorator.add(bCalculate2);//添加计算器2按钮
fDecorator.add(lTotal);//添加总标签
fDecorator.add(tTotal);//添加总文本字段
fDecorator.add(bHelp);//添加帮助按钮
bCalculate1.addActionListener(this);//添加一个要计算的操作侦听器按钮
bCalculate2.addActionListener(this);//将操作侦听器添加到Calculate2按钮
bHelp.addActionListener(this);//将操作侦听器添加到帮助按钮
cbflooding.addActionListener(this);//将操作侦听器添加到ComboBox
维度dim=Toolkit.getDefaultToolkit().getScreenSize();
fDecorator.setLocation(尺寸宽度/3-fDecorator.getSize().width/3,尺寸高度/3-fDecorator.getSize().height/3);
fDecorator.setSize(420130);//将帧大小设置为400×200
fDecorator.setVisible(true);//将frame设置为visible
}
@凌驾
public void actionPerformed(ActionEvent e)//操作侦听器
{
尝试//使用此块中的代码处理异常
{
JComboBox selectionBox=(JComboBox)e.getSource();//声明参数化的ComboBox selectionBox
String selectedFloor=(String)selectionBox.getSelectedItem();//将selectedFloor声明为组合框内的字符串
如果(selectedFloor.equals(“Wood£0.24”)//如果选择等于Wood
floorPrice=0.24;//分配floorPrice值0.24
else if(selectedFloor.equals(“陶瓷0.37”)//如果选择等于陶瓷
floorPrice=0.37;//分配floorPrice值0.37
else if(selectedFloor.equals(“石头0.86”)//如果选择等于石头
floorPrice=0.86;//分配floorPrice值0.86
else if(selectedFloor.equals(“Lino£1.24”)//如果选择等于Lino
floorPrice=1.24;//分配floorPrice值1.24
else if(selectedFloor.equals(“大理石1.76英镑”)//如果选择等于大理石
floorPrice=1.76;//分配floorPrice值1.76
else if(selectedFloor.equals(“层压板2.10”)//如果选择等于层压板
floorPrice=2.10;//分配floorPrice值2.10
else if(selectedFloor.equals(“竹价2.34”)//如果选择等于竹价
floorPrice=2.34;//分配floorPrice值2.34
else if(selectedFloor.equals(“地毯3.78英镑”)//如果选择等于地毯
floorPrice=3.78;//分配floorPrice值3.78
}
catch(异常a)//使用此
{
//如果遇到异常,则不执行任何操作,防止程序崩溃并处理e
DecimalFormat dc = new DecimalFormat("0.00");
String formattedText = dc.format(yourDouble);
DecimalFormat df = new DecimalFormat("#.00");
tSize.setText(Double.toString(df.format(Length * Width)));
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());
 }