Names: The Frame is called “simpleframe” and the Button is called “simplebutton”. You can change these names to anything that makes sense to you, make sure the names are all consistent.
import java.awt.*;
import java.awt.color.*;
import java.awt.event.*;
public class ButtonPressDemo { public static void main(String[] args){
Button simplebutton; //declare b to be a button ActionListener a = new MyActionListener1(); //declare a to be a method that listens to actions Frame simpleframe = new Frame("Java Action Listener Example"); // declare f to be a frame and
name it simpleframe.setSize(400, 200); // Set the size for your window simpleframe.setBackground(Color.green); // Change the color of the background simplebutton = new Button("Click me"); // Create a button simpleframe.add(simplebutton, BorderLayout.NORTH); // adding a button to a frame and positioning
it at the top simplebutton.addActionListener(a); // Calling the variable to trigger the action
//simpleframe.pack(); // Makes everything visible in the most efficient layout; Ignores the set size simpleframe.setVisible(true); // Makes the frame visible
}
}
// Triggers an action as to what happens when the button is clicked
class MyActionListener1 implements ActionListener {
public void actionPerformed(ActionEvent ae) { System.out.println("You have triggered an action by clicking the button"); // Prints the wordswhen the button is pushed
}
}
Enable screen reader
No comments:
Post a Comment