2010-08-15 1 views
0

사용자가 2 개의 입력란을 입력하려고합니다. 하나는 수영장의 볼륨이고 다른 하나는 오두막 욕조의 볼륨입니다. 이것은 각각의 가격을 계산하고, 내가 문제를 일으키는 것은 사용자가 수영장의 볼륨을 입력하면 온수 욕조에 대해 아무것도 입력 할 수 없으며 그 반대도 마찬가지입니다. 이것은 내가 지금까지 가지고있는 것이다. 이를 위해 2 개의 별도 필드가 필요합니까, 아니면 어떻게 할 수 있습니까?Java 버튼 질문

꽤 많은 문자열 오류 = ""; 한 번만 일련의 숫자를 입력하는 방법을 알아 내면 제거 할 수 있습니다. 다음은 계산 부분입니다. 코드의 다른 부분은 3 개의 레이블입니다.

pricePanel = new JPanel(new FlowLayout()); 

     final JRadioButton poolPrice= new JRadioButton("Pool"); 
     final JRadioButton tubPrice = new JRadioButton("Hot Tub"); 

     poolPrice.setSelected(true); 

     ButtonGroup group = new ButtonGroup(); 
     group.add(poolPrice); 
     group.add(tubPrice); 

     pricePanel.add(poolPrice); 
     pricePanel.add(tubPrice); 

     pricePanel.add(new JLabel("Enter the pool's volume: ")); 
     final JTextField poolField = new JTextField(10); 
     pricePanel.add(poolField); 

     pricePanel.add(new JLabel("Enter the tub's volume: ")); 
     final JTextField tubField = new JTextField(10); 
     pricePanel.add(tubField); 


     JButton calculatePrice = new JButton("Calculate Price"); 
     calculatePrice.setMnemonic('C'); 
     pricePanel.add(calculatePrice); 
     pricePanel.add(createExitButton()); 

     pricePanel.add(new JLabel("The price is:$ ")); 
     final JTextField priceField = new JTextField(10); 
     priceField.setEditable(false); 
     pricePanel.add(priceField); 


     calculatePrice.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 

        double pool = Double.parseDouble (poolField.getText()); 
        double tub = Double.parseDouble(tubField.getText()); 

        double price; 
        if (poolPrice.isSelected()) { 
         price = pool * 100; 
        } else { 
         price = tub * 75; 
        } 
        priceField.setText(df.format(price)); 
       } 
     }); 
    }; 


     ActionListener priceListener = new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       if (e.getSource() == poolPrice) { 
        tubLabel.setEnabled(false); 
        tubField.setEnabled(false); 
        messageArea.setVisible(true); 
       } else if (e.getSource() == tubPrice) { 
        poolLabel.setEnabled(false); 
        poolField.setEnabled(false); 
        messageArea.setVisible(true); 
       } 
      } 
     }; 


     poolPrice.addActionListener(priceListener); 
     tubPrice.addActionListener(priceListener); 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

hotTubsPanel = new JPanel(new FlowLayout()); 

    final JRadioButton roundTub = new JRadioButton("Round Tub"); 
    final JRadioButton ovalTub = new JRadioButton("Oval Tub"); 

    roundTub.setSelected(true); 

    ButtonGroup group = new ButtonGroup(); 
    group.add(roundTub); 
    group.add(ovalTub); 

    hotTubsPanel.add(roundTub); 
    hotTubsPanel.add(ovalTub); 

    hotTubsPanel.add(new JLabel("Enter the tub's length:  ")); 
    final JTextField lengthField = new JTextField(10); 
    hotTubsPanel.add(lengthField); 

    final JLabel widthLabel = new JLabel("Enter the tub's width*: "); 
    widthLabel.setEnabled(false); 
    hotTubsPanel.add(widthLabel); 

    final JTextField widthField = new JTextField(10); 
    widthField.setEnabled(false); 
    hotTubsPanel.add(widthField); 

    hotTubsPanel.add(new JLabel("Enter the tub's depth: ")); 
    final JTextField depthField = new JTextField(10); 
    hotTubsPanel.add(depthField); 

    JButton calculateVolume = new JButton("Calculate Volume"); 
    calculateVolume.setMnemonic('C'); 
    hotTubsPanel.add(calculateVolume); 
    hotTubsPanel.add(createExitButton()); 

    hotTubsPanel.add(new JLabel("The tub's volume is: ")); 
    final JTextField volumeField = new JTextField(10); 
    volumeField.setEditable(false); 
    hotTubsPanel.add(volumeField); 

    final JTextArea messageArea = createMessageArea(1, 25, 
      "*Width will be set to the same value as length"); 
    hotTubsPanel.add(messageArea); 

    calculateVolume.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      if (roundTub.isSelected()) { 
       widthField.setText(lengthField.getText()); 
      } 

      ValidationResult result = validateFields(new JTextField[] { 
        lengthField, widthField, depthField }); 

      String errors = ""; 
      if (result.filled != 3) { 
       errors += "Please fill out all fields! "; 
      } 
      if (result.valid != 3 && result.filled != result.valid) { 
       errors += "Please enter valid numbers!"; 
      } 

      if (errors != "") { 
       messageArea.setText(errors); 
       messageArea.setVisible(true); 
      } else { 
       messageArea.setVisible(false); 

       double length = Double.parseDouble(lengthField.getText()); 
       double width = Double.parseDouble(widthField.getText()); 
       double depth = Double.parseDouble(depthField.getText()); 

       double volume; 
       if (roundTub.isSelected()) { 
        volume = Math.PI * Math.pow(length/2.0, 2) * depth; 
       } else { 
        volume = Math.PI * Math.pow(length * width, 2) * depth; 
       } 
       volumeField.setText(df.format(volume)); 
      } 
     } 
    }); 

    ActionListener tubsListener = new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      if (e.getSource() == roundTub) { 
       widthLabel.setEnabled(false); 
       widthField.setEnabled(false); 
       widthField.setText(lengthField.getText()); 
       messageArea.setText("Tub's width set to length"); 
       messageArea.setVisible(true); 
      } else if (e.getSource() == ovalTub) { 
       widthLabel.setEnabled(true); 
       widthField.setEnabled(true); 
       messageArea.setVisible(false); 
      } 
     } 
    }; 
    roundTub.addActionListener(tubsListener); 
    ovalTub.addActionListener(tubsListener); 
} 
+1

어쩌면 텍스트 필드를 하나만 가질 수 있고 사용자가 원하는 제품 종류를 선택할 수 있도록 라디오 버튼을 가질 수 있습니다. (정확하게 질문을 이해하면 다소 혼란 스러웠습니다). – Stian

+0

하나의 입력에 대한 이유는 온수 욕조 가격 또는 수영장 가격에 대한 옵션을 갖고 있으며 두 필드 모두에 대해 하나의 출력 상자 만 있기 때문입니다. 나는 풀장 가격과 온수 욕조 가격대를 가질 수 있었지만, 단지 하나만 갖는 것이 더 효율적이라고 생각했습니다. 나는 그들이 생각하지 않은 수영장이나 온수 욕조를 선택하기 위해 라디오 버튼을 할 수있다. – David

답변

2

두 텍스트 필드와 하나 개의 결과 필드 사용자에게 혼동을 줄 수 있습니다. 하나의 결과 필드 만있을 경우 하나의 텍스트 필드도 있어야합니다. Stian이 제안한 라디오 버튼은 두 개의 버튼 (풀과 뜨거운 욕조 용 버튼이 하나만 있으면 작동합니다) (다른 가격을 얻으려면 한 번의 클릭만으로됩니다). 결과 필드에는 "Pool price : $ XX.XX"또는 "Hot tub price : $ XX.XX"와 같이 계산 된 값이 표시되어야합니다. 버튼 아이디어를 사용하고 "풀"및 "핫 터브"버튼을 표시 한 경우 setText(e.getActionCommand()+" price:"+price);과 같은 결과가 표시 될 수 있습니다.

또한 if (errors != "")은 항상 true입니다. errors 개체가 새로 만드는 String 개체와 동일한 개체인지 테스트하고 있습니다. 그것은 결코 존재하지 않을 것이다. 대신 if (!errors.equals("")) 또는 if (errors.length()!=0)을 테스트해야합니다.

+0

자, 라디오 버튼을 사용하도록 프로그램을 편집 했으므로, 다음과 같은 이유로이 오류가 발생합니다. poolPrice.addActionListener (priceListener); tubPrice.addActionListener (priceListener); 토큰 "priceListener"에 구문 오류가 있습니다.이 토큰 다음에 VariableDeclaratorId가 필요합니다 ... 하지만이 설정은 잘 작동하는 다른 방법으로 사용 했으므로 confuzzled입니다. – David

+0

해당 오류는 일반적으로 (메서드 정의에서) 매개 변수의 형식을 선언 할 때 발생하지만 해당 이름은 선언하지 않습니다. 나는 여기서 그런 일이 일어나지 않는다는 것을 알기 때문에 솔직히 조금 혼란 스럽다. 컨텍스트를 볼 수 있도록 코드를 조금 더 게시 할 수 있습니까? – qmega

+0

그게 전부 코드입니다. 더 나은 이해를위한 섹션, 프로그램을위한 탭입니다. 나는 프로그램의 또 다른 탭을 게시 할 수 있지만이 프로그램에 어떤 중요성도 있어서는 안됩니다. – David