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