我试图建立一个百分比程序,找出一个数字的百分比。我想把两个用户输入的数字用于jtextfield命中jbutton并将答案显示在列为结果的另一个jtextfield中。任何想法如何做到我知道它需要动作听众,但我不知道从那里去哪里。这就是我所拥有的,我打印出我想要的东西,不知道必须让actionlistener工作。
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;
}
}
}
}
答案 0 :(得分:1)
您的代码的主要问题是您没有设置保存结果的JTextField的文本。只需在此JTextField上调用setText(...)
并传入表示结果的String即可完成此操作。您还需要删除JTextField中的无意义文本“Type”,因为它们可能会搞乱,除非您想要将FocusListener添加到所有文本字段,以便在focusGained上它将选择该字段的所有内容。
您还需要重新命名您的变量,如上面的评论中所述。
答案 1 :(得分:0)
您应该使用setText()方法在适当的字段中设置结果。但是我有一个问题:你说两个用户同时设置他们的输入,我的意思是你的应用程序是分布式的吗?换句话说,用户在网络中并使用它!?