如果keyPressed正在处理中

时间:2016-12-07 01:15:00

标签: processing

我正在尝试制作一个简单的程序来计算贷款利息。我在这里的代码有效但只会在按下'c'键时显示结果。如何更改逻辑,以便在按下“c”后,屏幕上会显示结果。任何帮助都是先进的。

   import controlP5.*;
ControlP5 cp5;
Textfield loan; 
Textfield interest;
Textfield months;
Button calculate;
Double loan1;
Double months1;
double interest1;
void setup(){
size(700,400);
PFont font = createFont("arial",20);
cp5 = new ControlP5(this);
loan =  cp5.addTextfield("Loan Amount")
 .setPosition(20,100)
 .setSize(200,40)
 .setFont(font)
 .setFocus(true)
 .setColor(color(255,0,0));
 loan.setInputFilter(ControlP5.INTEGER)
 ;         
  interest =  cp5.addTextfield("Interest Rate")
 .setPosition(20,190)
 .setSize(200,40)
 .setFont(font)
 .setFocus(false)
 .setColor(color(255,0,0));
 interest.setInputFilter(ControlP5.INTEGER)
 ;
  months =  cp5.addTextfield("Length in months")
 .setPosition(450,100)
 .setSize(200,40)
 .setFont(font)
 .setFocus(false)
 .setColor(color(255,0,0));
 months.setInputFilter(ControlP5.INTEGER)
 ;
  }
 void draw(){
background(120);
fill(255);
noStroke();
rect(0,0,750,70);
fill(20);
textSize(32);
text("Monthly Loan Repayment Calculator ", 70, 45); 
fill(41,194,214);
ellipse(340,170,130,130);
fill(24,74,140);
ellipse(340,170,125,125);
fill(255);
textSize(18);
text("Enter 'c'",305,155);
text("to calculate", 295,175);
fill(0);
rect(0,260,700,1);

String loan2 =     loan.getText();
String interest2 = interest.getText();
String months2 =   months.getText();

 if(keyPressed)
{
    if(key=='c'||key=='C'&&!loan2.equals("")&&!interest2.equals("")&&!months2.equals         ("")){
loan1 = Double.parseDouble(loan2);
interest1 = Double.parseDouble(interest2);
months1 = Double.parseDouble(months2);

interest1=interest1/100/12;
double payment = (loan1*interest1)/(1-Math.pow(interest1+1,-months1));
payment = (double)Math.round(payment*100)/100;
//println(payment);
//text(payment,20,20);

int total = (int)payment;

text(total,200,350);
  }


}
}

1 个答案:

答案 0 :(得分:1)

如果是否按下某个键,您当前正在使用draw()方法进行检查,如果当前按下了该键,则仅显示显示兴趣计算的文本字段。这就是

if (keyPressed) {
...

正在做。一个更好的方法是覆盖实际的keyPressed()方法(在draw()之外)并在' c'之后设置一个布尔标志。键是按下的。因此,在程序的顶部,您可以创建类似的内容:

boolean showInterestText = false;

然后,您将更改两个嵌套的if语句

 if(keyPressed)
 {
    if(key=='c'||key=='C'&&!loan2.equals("")&&!interest2.equals("")&&!months2.equals         ("")){
 ...

到单个if语句,如

if (showInterestText) {
...

最后,覆盖keyPressed()方法,将showInterestText设置为true,如果' c'键是按下的。类似的东西:

void keyPressed() {
    if (key == 'c' || key == 'C') {
        showInterestText = true;
    }
}

这样,在不再按下键后,showInterestText布尔值保持为true。

PS。欢迎来到stackoverflow,下次发布时请格式化代码,使其可读。