我希望我的程序执行带有文本字段的 JFrame:名字、姓氏、帐户状态和提款金额,向用户询问该信息,然后显示这样的消息框:“你好约翰·史密斯,提款后,你当前的帐户状态是:(提款后的状态)。我做了我能做的唯一方法(起初我想创建一个单独的类,我将在其中解析状态和提款金额,然后进行计算,但我有问题)。所以我在 Card 类中做到了。问题是(这就是我想问你的)程序不仅不进行计算,而且根本不编译。当我从我的程序中删除计算代码,它可以编译,但显而易见的是,仅在消息框中返回“HellofirstNamelastName”。
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);
}
}
}
最佳答案
对不起,是我的错。您在类里面发表的所有陈述都是赋值语句,因此技术上它们是允许的,但它们的位置仍然给您带来问题。
您的问题是您已经在类中将计算作为赋值语句的一部分进行了,因此您在用户有机会输入数据之前进行计算。
相反,在 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) {
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);
}
}
}
关于java - 在 JFrame MessageBox 中给出计算结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21466287/