如何编写代码以从JTextField
获取文本并将其转换为双精度字符?
我用amountField
创建了一个银行帐户类和一个银行帐户GUI,以显示我希望提取和存入的金额。
如何使用public void actionPerformed(ActionEvent e)
方法编写代码以从amountField
获取文本并将其转换为double?
我想输入帐户详细信息,并能够在将值存储在字符串中的同时提款和存款
public class BankAccountGUI extends JFrame implements ActionListener
{
private Label amountLabel = new Label("Amount");
private JTextField amountField = new JTextField(5);
private JButton depositButton = new JButton("DEPOSIT");
private JButton withdrawButton = new JButton("WITHDRAW");
private Label balanceLabel = new Label("Starting Balance = 0" );
private JPanel topPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
private JPanel middlePanel = new JPanel();
BankAccount myAccount = new BankAccount("James","12345");
// declare a new BankAccount object (myAccount) with account number and name of your choice here
public BankAccountGUI()
{
setTitle("BankAccount GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(340, 145);
setLocation(300,300);
depositButton.addActionListener(this);
withdrawButton.addActionListener(this);
topPanel.add(amountLabel);
topPanel.add(amountField);
bottomPanel.add(balanceLabel);
middlePanel.add(depositButton);
middlePanel.add(withdrawButton);
add (BorderLayout.NORTH, topPanel);
add(BorderLayout.SOUTH, bottomPanel);
add(BorderLayout.CENTER, middlePanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//What goes here?
}
}
答案 0 :(得分:1)
您可能要尝试使用Double.parseDouble(string)。 例如:
List<SearchItem> searchResults = new ArrayList<>(serverResults);
keyboardInstance.get().mAdapter.updateResults(searchResults);
keyboardInstance.get().resultListView.setAdapter(keyboardInstance.get().mAdapter);
答案 1 :(得分:0)
这里有很多事情您需要做不同的事情。 简而言之,您正在寻找“ JTextField.getText()”和“ Double.parseDouble()”
depositButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Get the Text Value out of the UI Component
String rawAmount=amountField.getText();
//Convert that value to Double
try{
Double convertedValue = Double.parseDouble(rawAmount);
//Do stuff with the convertedValue
}catch(Exception e){
System.out.println("Not A Double Value");
}
}
});
对于每个按钮,还应该使用单独的侦听器,以免您尝试以编程方式确定哪个按钮生成了事件。
请参阅JTextField的文档