2014-01-30 74 views
1

我希望我的程序使用文本字段執行JFrame:名字,姓氏,賬戶狀態和提款金額,向用戶詢問該信息,然後顯示如下消息框:「 John Smith,在你退出之後,你目前的賬戶狀態是:(退出後的狀態),我這樣做是唯一的辦法(起初我想創建一個單獨的班級,在那裏我會解析狀態和提款額,然後進行計算,但是我遇到了問題)所以我在Card類中做了這個問題(這是我想問你的),該程序不僅沒有進行計算,而且它也沒有當我從程序中刪除計算代碼時,它會進行編譯,但是很明顯,只會在消息框中返回「Hello firstName lastName」。在JFrame MessageBox中給出計算結果

public class Card extends JFrame { 

    private JTextField firstName; 
    private JTextField lastName; 
    private JTextField state; 
    private JTextField withdrawal; 
    private JButton accept; 


    public Card() { 
     super("Cash Machine"); 
     setLayout(new FlowLayout()); 

     firstName = new JTextField("First name"); 
     add(firstName); 

     lastName = new JTextField("Last name"); 
     add(lastName); 

     state = new JTextField("Current account state"); 
     add(state); 

     withdrawal = new JTextField("Amount of withdrawal"); 
     add(withdrawal); 

     accept = new JButton("Accept"); 
     add(accept); 


     newHandler handler = new newHandler(); 
     accept.addActionListener(handler); 

    } 
    String state1 = state.getText(); 
    int state2 = Integer.parseInt(state1); 
    String withdrawal1 = withdrawal.getText(); 
    int withdrawal2 = Integer.parseInt(withdrawal1); 
    int finalState = state2 - withdrawal2; 



    private class newHandler implements ActionListener { 

     ArrayList<String> first_names = new ArrayList<String>(); 
     ArrayList<String> last_names = new ArrayList<String>(); 
     public void actionPerformed(ActionEvent event) { 


      // SHOWING THE FINAL MESSAGE BOX 
      if(event.getSource()==accept) 

       JOptionPane.showMessageDialog(null, "Hello " + firstName.getText() + " " + lastName.getText() + " " + state.getText() + " .Your current account state is: " + finalState); 
      } 
      }  
     } 

回答

2

對不起,我的壞。你在班上的所有陳述都是任務陳述,所以在技術上他們被允許,但他們的位置是仍然給你的問題。

你的問題是你已經在課堂上把你的計算作爲賦值語句的一部分,所以你在計算之前用戶有機會輸入數據。

取而代之,請在處理程序類中進行計算,以便文本字段中包含一些數據。

事情是這樣:

// String state1 = state.getText(); 
// int state2 = Integer.parseInt(state1); 
// String withdrawal1 = withdrawal.getText(); 
// int withdrawal2 = Integer.parseInt(withdrawal1); 
// int finalState = state2 - withdrawal2; 


private class newHandler implements ActionListener { 
    ArrayList<String> first_names = new ArrayList<String>(); 
    ArrayList<String> last_names = new ArrayList<String>(); 

    public void actionPerformed(ActionEvent event) { 

    // SHOWING THE FINAL MESSAGE BOX 
    if (event.getSource() == accept) { 

     String state1 = state.getText(); 
     int state2 = Integer.parseInt(state1); 
     String withdrawal1 = withdrawal.getText(); 
     int withdrawal2 = Integer.parseInt(withdrawal1); 
     int finalState = state2 - withdrawal2; 

     JOptionPane.showMessageDialog(null, "Hello " + firstName.getText() 
       + " " + lastName.getText() + " " + state.getText() 
       + " .Your current account state is: " + finalState); 
    } 
    } 
}