Sunday, January 24, 2016
Cylinder - Action Event Option 2
package actionEventOpt2;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
/**
*
* @author zbawk
*/
public class CylinderFrame extends javax.swing.JFrame {
/**
* Creates new form CylinderFrame
*/
public CylinderFrame() {
initComponents();
//Z.B: Second step
//register Cylinder button with CylinderButtonListener to handle
//this button click (action) event
//1. Create an instance of CylinderButtonListener
CylinderButtonListener cylinderListener = new CylinderButtonListener();
//2. use addActionListener method to register the button
jbtnCylinderPAV.addActionListener(cylinderListener);
//you could do it in a single statement
// jbtnCylinderPAV.addActionListener(new CylinderButtonListener());
//ZB.Step 4;
//register clear button with ClearListener
jbtnClear.addActionListener(new ClearListener());
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JButton jbtnClear;
private javax.swing.JButton jbtnCylinderPAV;
private javax.swing.JTextField jtxtHeight;
private javax.swing.JTextField jtxtRadius;
// End of variables declaration
//Z.B: define an inner class to listen for click (action) event of cylinder button
//for this class to listen for action events it must implement the
//ActionListener interface
private class CylinderButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//Code here runs when a button (associated or is registered with this class is clicked)
//read data from user
double r = Double.parseDouble(jtxtRadius.getText());
double h = Double.parseDouble(jtxtHeight.getText());
//compute
double area = 2*Math.PI*r*h;
double perimeter = 2*Math.PI*r;
double volume = Math.PI*r*h;
//display results
//Create decimal format
DecimalFormat df = new DecimalFormat("#.##");
jTextArea1.setText("Perimeter = " + df.format(perimeter) + "\n" +
"area = " + df.format(area) + "\n" +
"volume = "+ df.format(volume));
}
}
//ZB: Step 3
//an inner listener class for the clear button
private class ClearListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
//the clear button will be associated with this class
jtxtHeight.setText("");
jtxtRadius.setText("");
jTextArea1.setText("");
}
}
}//end of JFrame (this frame)
Labels:
Java
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment