我試圖建立一個百分比程序,發現一個數字的百分比從另一個數字。我想爲jtextfield輸入兩個用戶輸入的數字,並將結果顯示在另一個作爲結果列出的jtextfield中。任何想法如何做到這一點我知道它需要動作監聽器,但我不知道從那裏去哪裏。這是我得到它打印出我想要的只是不知道必須讓actionlistener工作。圖形用戶界面的Java - 如何使用2個用戶輸入的數字來獲得答案
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;
}
}
}
}
請告訴我們它是如何工作的。詳細信息*很重要。祝你好運。 –
此外,你會想要重命名你的變量,給他們的名字是有道理的。從現在開始,更容易調試一個名爲「field4」的變量或名爲「resultsField」的變量? –