int[] x = new int[10];
Scanner scan = new Scanner(System.in);
for(int i = 0; i < x.length; i++){
System.out.println("Enter number " + (i+1));
x[i] = scan.nextInt();
}
Event-driven programming is different, though. Rather than placing so much control on gathering input, we focus on responding to that input. So basically, when a button is clicked, we write the code to respond. When a key is pressed, or the mouse moved, etc., we respond to those respective events. This is how GUI programming is, as well as a lot of Game Programming. So if the user doesn't select something, then our program never responds. This may not be extremely clear right now, but after we examine the components of an Event-Driven model, I think the differences will become more apparent.
In any Event-driven model, we have three components: the trigger, the listener, and the response. The trigger is usually something the users interact with (like a JButton), but not always (in the case of Swing Timer). Basically, it fires an event. This is where the Listener comes in. As a trigger cannot listen for its own events, we need a separate component to do such. The Listener basically invokes the response.
An analogy for the event-driven model would be a light switch. We have the trigger (the switch), the Listener (the wiring), and the response (the light turning on). In addition, it is there for the user to click at will, but we are not notifying and prompting them to turn on the light.
A basic example illustrating the event-driven model in Java, commented to identify the trigger, listener, and response.
//we have a class which will display a window
//and listen for the button clicks
public class MyFrame extends JFrame implements ActionListener{
private JButton button = new JButton();
private int count = 0;
public MyFrame(){
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(button);
//we are telling button that it has a listener
//for its ActionEvent, marking the JButton as the trigger
//and this object as the listener
button.addActionListener(this);
this.add(button);
this.setVisible(true);
}
//this is our response
//when the listener is notified of an event
//being fired, it will invoke this method
public void actionPerformed(ActionEvent e){
button.setText("I have been clicked " + (++count) + " times");
}
}








MultiQuote





|