Last active
December 15, 2015 23:49
-
-
Save ljdelight/5342768 to your computer and use it in GitHub Desktop.
Simple program to demonstrate how to register an event with a button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Simple program to demonstrate how to register an event with a button. | |
// | |
// There are two inputs, a result field, and a button. When the button is pushed, | |
// an event is fired which finds the root of the sum of the squares. | |
// | |
import java.awt.event.*; | |
import javax.swing.*; | |
public class SimpleEvent extends JFrame implements ActionListener { | |
JTextField field_1 = new JTextField("3",20); | |
JTextField field_2 = new JTextField("4",20); | |
JTextField field_result = new JTextField(20); | |
JButton button_add = new JButton("FIND HYPOTENUSE"); | |
public static void main(String[] args) { | |
SimpleEvent myWindow = new SimpleEvent("Pythagorean"); | |
myWindow.setSize(350,200); | |
myWindow.setVisible(true); | |
} | |
public SimpleEvent(String title) { | |
super(title); | |
setLayout(new java.awt.FlowLayout()); | |
field_result.setEditable(false); | |
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
this.add(field_1); | |
this.add(field_2); | |
this.add(field_result); | |
this.add(button_add); | |
// !! This is the most important line of code for this little program. | |
// Notice the method signature looks like: void addActionListener( ActionListener ). So, | |
// as a parameter it takes an ActionListener, which SimpleEvent implements and actionPerformed | |
// is implemented. Thus when the butten triggers an event, the actionPerformed method is called | |
// and the fields are updated. | |
// | |
// See http://docs.oracle.com/javase/7/docs/api/java/awt/TextField.html#addActionListener(java.awt.event.ActionListener) | |
// | |
button_add.addActionListener(this); | |
} | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
// if the input fields are empty, do nothing | |
if ( field_1.getText().length() > 0 && field_1.getText().length() > 0 ) { | |
try { | |
double d1 = Double.parseDouble( field_1.getText() ); | |
double d2 = Double.parseDouble( field_2.getText() ); | |
Double result = Math.sqrt( d1*d1 + d2*d2 ); | |
field_result.setText(result.toString()); | |
} catch (NumberFormatException err) { | |
field_result.setText("Error"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment