2015-03-08 109 views
3

我一直在搜索这个问题的解决方案,我可能找到了它,但我对编程非常陌生,所以我的理解水平最好是平庸的。JTextField只显示2位小数

我有一个计算发生在两个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)考虑使用'JSpinner'与['SpinnerNumberModel'](https://docs.oracle.com/javase/8/docs/api /javax/swing/SpinnerNumberModel.html)而不是文本字段。 2)但除此之外,请看['DecimalFormat'](https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html)。3)catch(Exception a){ }'不要忽视异常!这应该是:catch(Exception a){e.printStackTrace(); (4)'fDecorator.setSize(420,130);'最好'fDecorator.pack();'.. – 2015-03-08 16:52:59

+1

.. 5)'double Length..'请学习常用的Java命名规则(命名约定 - 例如'EachWordUpperCaseClass ','firstWordLowerCaseMethod()','firstWordLowerCaseAttribute',除非它是'UPPER_CASE_CONSTANT')并且一致地使用它。 – 2015-03-08 16:56:40

回答

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

哪里yourDouble是双要格式化。

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

0

尝试类似:

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

我试过了,它没有工作!虽然我理解它背后的前提。 Eclipse给了我一个错误,告诉我删除了我需要的toString。 – Starmaderp 2015-03-08 17:05:41

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