在 Java 中集成递归的 GUI 编程的一点帮助

A little assistance with my GUI programming integrated with recursion in Java

Java 我的 GUI 程序需要一些帮助。我的程序使用 GUI 界面接收用户的第 n 个术语;然后计算该术语的斐波那契数并将其打印在界面上。请看看我的程序。我想知道两件事:

  1. 如何将变量分配给 fib 函数中的 return 值?
  2. 将变量设置为 return 值后,我想在我的 actionPerformed 方法中访问该变量,以便将其打印到界面。

计划

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class GUIwithRecursion extends Applet implements ActionListener
{
public static TextField numberTF = new TextField ();
public static TextField fibTF    = new TextField();

int result = fib(numberN);

public void init()
{
setBackground(Color.magenta);
Label     numberLB = new Label("n= ");
Button    calcBN   = new Button("Calculate");
Label     fibLB    = new Label("fib(n)= ");

setLayout(null);
numberLB.setBounds(10, 30, 100, 20);
numberTF.setBounds(10, 50, 100, 20);
numberTF.setBackground(Color.yellow);
fibLB.setBounds(10, 70, 100, 20);
fibTF.setBounds(10, 90, 100, 20);
fibTF.setBackground(Color.red);
calcBN.setBounds(10, 110, 100, 20);

add(numberLB);
add(numberTF);
add(fibLB);
add(fibTF);
add(calcBN);

calcBN.addActionListener(this);
}

public static int fib(int numberN)
{
    if (numberN<=1)
    {return 1;}
    
    else
    {return fib(numberN-1)+fib(numberN-2);}
}

public void actionPerformed(ActionEvent e)
{

    int result = fib(numberN);
    fibTF.setText(Integer.toString(result));
    
}
}

1) How do I assign a variable to the return value in the fib function?

int number = Integer.parseInt(numberTF.getText());
int result = fib(number);

2) After setting a variable to the return value, I want to have an access to that variable in my actionPerformed function, so I can print it to the interface.

更好的解决方案是在 actionPerformed 方法中执行计算

public void actionPerformed(ActionEvent e) {
    int number = Integer.parseInt(numberTF.getText());
    int result = fib(number);
    fibTF.setText(Integer.toString(result));
}

下一个问题是,为什么 Applet 以及为什么使用 AWT 库?两者都已被 Swing(现在是 JavaFX)取代,applet 现在已被大多数浏览器主动阻止。

您通常会获得对 Swing 和 JavaFX 更好的支持,现在大多数人都在使用这些库来开发纯 AWT

避免使用 null 布局,像素完美布局是现代 ui 设计中的一种错觉。影响组件个体大小的因素太多,none 是您可以控制的。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正

查看 Laying Out Components Within a Container 了解更多详情