了解java ActionListener时遇到的问题-Performed(ActionEvent e)
|
我必须为Fibonacci程序编写代码,该程序用两个文本框和一个按钮来构建GUI。用户在文本框1中输入数字,然后单击按钮,然后放置该数字的斐波那契。我在理解java的actionPerformed部分时遇到问题,将不胜感激。这是我的代码:有3个文件。
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
没有找到相关结果
已邀请:
1 个回复
队辅坟阮阶
在这里,您声明一个实现
接口的类
,以告知他可以处理事件的按钮(使用with6ѭ方法) 我希望这一点可以弄清楚它是如何工作的。