0
我必须为Fibonacci程序编写代码,该程序构建一个带有两个文本框和一个按钮的GUI。用户在文本框1中输入一个数字,然后单击该按钮,然后放置该数字的斐波纳契数。我在理解java的actionPerformed部分时遇到问题,并希望得到任何帮助。这是我的代码:有3个文件。理解java的问题ActionListener - 执行(ActionEvent e)
Fibonacci.java
public class Fibonacci{
int Fib (int n){
int in1=1,in2=1;
int sum=0;//initial value
int index=1;
while (index<n){
sum=in1+in2;//sum=the sum of 2 values;
in1=in2;//in1 gets in2
in2=sum;//in2 gets sum
index++; //increment index
}
return sum;
}
}
FibonacciJPanel.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FibonacciJPanel extends JPanel implements ActionListener
{ private JTextField inField = new JTextField(15); //GUI components
private JTextField resultField = new JTextField(15);
private JLabel prompt1 = new JLabel("Input Fibonacci>>");
private JLabel prompt2 = new JLabel("Conversion Result:");
private JButton FibonacciButton = new JButton("Fibonacci of the input");
private JPanel panelN = new JPanel(); //Panels
private JPanel panelC = new JPanel();
private JPanel panelS = new JPanel();
private Fibonacci F = new Fibonacci();
public FibonacciJPanel() //Set up user panel
{ setLayout(new BorderLayout()); //User BorderLayout
panelN.setLayout(new BorderLayout());
panelC.setLayout(new BorderLayout());
panelS.setLayout(new BorderLayout());
panelN.add("North", prompt1); //Input elements
panelN.add("South", inField);
panelC.add("West", FibonacciButton); //Control button
panelS.add("North", prompt2); //Output elements
panelS.add("South", resultField);
add("North", panelN); //Input at the top
add("Center", panelC); //buttons in the center
add("South", panelS); //Result at the bottom
FibonacciButton.addActionListener(this); //Register with listeners
setSize(175,200);
} //FibonacciJPanel
public void actionPerformed(ActionEvent e)
{
String inputStr = inField.getText(); //user input
int userInput = Integer.parseInt(inputStr); //convert to integer
boolean result=false;
if (e.getSource() == FibonacciButton); //Process and report
{
result = fc.sum(userInput);
resultField.setText("result");
} //if
}//actionPerformed()
}
FibonacciJApplet.java
import javax.swing.*;
public class FibonacciJApplet extends JApplet
{ public void init()
{ getContentPane().add(new FibonacciJPanel());
} // init()
} // Fibonacci class
我明白了ActionListener的作用,我想这只是ActionPerformed下的代码,我无法弄清楚如何让它做我需要的。 – user709078 2011-04-16 01:59:02
我发现编程只需要弄清楚如何将结果限制为最大值40 – user709078 2011-04-16 16:00:03