有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我需要一些关于Java GUI程序的帮助。我的程序使用GUI界面从用户那里获取第n个术语;然后,它计算该项的斐波那契数,并将其打印在界面中。请看一下我的节目。我想知道两件事:

  1. 如何在fib函数中为返回值分配变量
  2. 将变量设置为返回值后,我希望在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) 个答案

  1. # 1 楼答案

    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)取代,小程序现在被大多数浏览器主动屏蔽

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

    避免使用null布局,像素完美的布局在现代ui设计中是一种错觉。影响零部件单个尺寸的因素太多,您无法控制。Swing的设计初衷是与布局管理器一起工作,丢弃这些布局管理器将导致无止境的问题,您将花费越来越多的时间来纠正这些问题

    有关更多详细信息,请查看Laying Out Components Within a Container