Page 699 - Introduction to Programming with Java: A Problem Solving Approach
P. 699

                16.12 JButton Component 665
 /************************************************************
*
FactorialButton.java
Dean & Dean
When user clicks button or presses Enter in input text box,
entered number's factorial displays in the output text box.
************************************************************/
*
*
*
*
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FactorialButton extends JFrame
{
private static final int WIDTH = 300;
private static final int HEIGHT = 100;
private JTextField xBox; // holds user entry
private JTextField xfBox; // holds generated factorial
//*********************************************************
public FactorialButton()
{
setTitle("Factorial Calculator");
setSize(WIDTH, HEIGHT);
setLayout(newAFplowaLagyout()P);DF Enhancer setDefaultCloseOperation(EXIT_ON_CLOSE); createContents();
setVisible(true);
// end FactorialButton constructor
//*********************************************************
}
private void createContents()
{
  }
JLabel xLabel = new JLabel("x:");
JLabel xfLabel = new JLabel("x!:");
JButton btn = new JButton("Factorial");
Listener listener = new Listener();
xBox = new JTextField(2);
xfBox = new JTextField(10);
xfBox.setEditable(false);
add(xLabel);
add(xBox);
add(xfLabel);
add(xfBox);
add(btn);
xBox.addActionListener(listener);
btn.addActionListener(listener);
// end createContents
Here we register the same listener with two different components.
  Figure 16.8a FactorialButton program—part A
















































   697   698   699   700   701