Problem:
See the output

Output:
Solution:
//********************FibonacciNumbersApp.java*********/ import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class FibonacciNumbersApp extends JFrame { private JLabel inputLabel, resultLabel; private JTextField InputTextField; private JButton goButton; private int number; private JPanel northPanel, southPanel; private FibonacciWorker worker; public FibonacciNumbersApp() { northPanel = createNorthPanel(); southPanel = createSouthPanel(); Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(2,1)); contentPane.add(northPanel); contentPane.add(southPanel); } private JPanel createNorthPanel() { JPanel panel = new JPanel(); inputLabel = new JLabel("Get The Fibonnaci of: "); InputTextField = new JTextField(6); panel.add(inputLabel); panel.add(InputTextField); return panel; } private JPanel createSouthPanel() { JPanel panel = new JPanel(); goButton = new JButton("Go"); goButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { number = Integer.parseInt(InputTextField.getText()); } catch (NumberFormatException e1) { resultLabel.setText("Input must be numeric!"); return; } worker = new FibonacciWorker(number, resultLabel); worker.execute(); resultLabel.setText("Calculating.."); } }); resultLabel = new JLabel("Ouptut will appear here: "); panel.add(goButton); panel.add(resultLabel); return panel; } public static void main(String[] args) { FibonacciNumbersApp demo = new FibonacciNumbersApp(); demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); demo.setSize(350, 150); demo.setVisible(true); demo.setResizable(false); demo.setLocationRelativeTo(null); } } //********************FibonacciWorker.java*********/ import java.util.concurrent.ExecutionException; import javax.swing.JLabel; import javax.swing.SwingWorker; public class FibonacciWorker extends SwingWorker<Long, Object> { private int number; private JLabel resultLabel; public FibonacciWorker(int number, JLabel resultLabel) { this.number = number; this.resultLabel = resultLabel; } @Override protected java.lang.Long doInBackground() throws Exception { return fibonacci(number); } @Override protected void done() { try { resultLabel.setText(get().toString()); } catch (InterruptedException e) { resultLabel.setText("Interupted while waiting for result"); } catch (ExecutionException e) { resultLabel.setText("Error encountred during execution"); } } public long fibonacci(int n) { if(n==0 || n==1) return n; else return fibonacci(n-1) + fibonacci(n-2); } }
No comments :
Post a Comment