我的GUI编程与Java中的递归集成的一点帮助
我需要一些关于Java GUI程序的帮助。我的程序使用GUI界面从用户那里获取第n个术语;然后,它计算该项的斐波那契数,并将其打印在界面中。请看一下我的节目。我想知道两件事:
- 如何在fib函数中为返回值分配变量李>
- 将变量设置为返回值后,我希望在
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 楼答案
更好的解决方案是使用
actionPerformed
方法进行计算下一个问题是,为什么
Applet
以及为什么使用AWT库?这两个版本都被Swing(现在是JavaFX)取代,小程序现在被大多数浏览器主动屏蔽通常,您将获得对Swing和JavaFX的更好支持,现在大多数人都在使用这些库来开发纯AWT
避免使用
null
布局,像素完美的布局在现代ui设计中是一种错觉。影响零部件单个尺寸的因素太多,您无法控制。Swing的设计初衷是与布局管理器一起工作,丢弃这些布局管理器将导致无止境的问题,您将花费越来越多的时间来纠正这些问题有关更多详细信息,请查看Laying Out Components Within a Container