我正在尝试构建一个百分比程序,用于查找一个数字与另一个数字的百分比。我想为 jtextfield 获取两个用户输入的数字,点击 jbutton 并将答案显示在作为结果列出的另一个 jtextfield 中。知道如何做到这一点,我知道它需要 Action 监听器,但我不知道从那里去哪里。这是我所拥有的,我可以用它打印出我想要的内容,只是不知道必须让 Action 监听器工作。
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class WeightGUI extends JFrame{
private JLabel label1;
private JTextField field1;
private JLabel label2;
private JTextField field2;
private JLabel label3;
private JTextField field3;
private JLabel label4;
private JTextField field4;
private JButton button1;
private JButton button2;
private JButton button3;
public WeightGUI () {
super( "Percentage Weight Loss Calculator");
setLayout( new FlowLayout() );
label1 = new JLabel ("Starting Weight ");
field1 = new JTextField ("Type");
label2 = new JLabel ("Last Week Weight");
field2 = new JTextField ("Type");
label3 = new JLabel ("Current Weight");
field3 = new JTextField ("Type");
label4 = new JLabel ("Percentage Lost");
field4 = new JTextField ("Results");
button1 = new JButton (" Calculate Percent Total");
button2 = new JButton (" Calculate Percent Week");
button3 = new JButton (" Calculate Percent from last weight");
label1 = new JLabel( "Starting Weight");
add(label1);
field1 = new JTextField("Type");
add (field1);
label2 = new JLabel( "Last Week Weight");
add(label2);
field3 = new JTextField(10);
add (field2);
label3 = new JLabel( "Current Weight");
add(label3);
field3 = new JTextField("Type");
add (field3);
label4 = new JLabel( "Percentage Lost");
add( label4 );
field4 = new JTextField("Results");
field4.setEditable(false);
add (field4);
button1 = new JButton ("Calculate Total Percent");
add( button1 );
button2 = new JButton ("Calculate Percent from last Weight");
add( button2 );
button3 = new JButton ("Calculate Weekly Percent");
add( button3 );
thehandler handler = new thehandler();
button1.addActionListener(handler);
thehandler handler1 = new thehandler();
button2.addActionListener(handler1);
thehandler handler2 = new thehandler();
button3.addActionListener(handler2);
}
private class thehandler implements ActionListener {
public void actionPerformed (ActionEvent e){
int sw;
int lw;
int cw;
double weight = 0 ;
String inputString;
inputString = field1.getText();
inputString = field2.getText();
inputString = field3.getText();
sw = Integer.parseInt(inputString);
lw = Integer.parseInt(inputString);
cw = Integer.parseInt(inputString);
if(e.getSource() == button1) {
weight = (sw - cw) / sw;
}
else if(e.getSource() == button2) {
weight = (lw - cw) / sw;
}
else if(e.getSource() == button3){
weight = (lw - cw)/ lw;
}
}
}
}
最佳答案
您的代码的主要问题是您没有设置保存结果的 JTextField 的文本。只需在此 JTextField 上调用 setText(...)
并传入表示结果的字符串即可完成此操作。您还需要删除 JTextFields 中的无意义文本“Type”,因为它们可能会把事情搞砸,除非您想向所有文本字段添加 FocusListener,以便在 focusGained 上它将选择该字段的所有内容。
您还需要按照我上面的评论中所述重新命名变量。
关于java - GUI Java-如何使用2个用户输入的数字来得到答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088229/