Java Reference
In-Depth Information
btnColor.addActionListener(this);
getContentPane().add(btnOffOn);
getContentPane().add(btnColor);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ev) {
String action = ev.getActionCommand();
System.err.println("Got action "+action);
switch (action) {
case ACTION_ON:
isLightOn = true;
getContentPane().setBackground(COLORS[currentColor]);
((JButton) ev.getSource()).setText("Lights Off");
((JButton) ev.getSource()).setActionCommand(ACTION_OFF);
break;
case ACTION_OFF:
isLightOn = false;
getContentPane().setBackground(Color.black);
((JButton) ev.getSource()).setText("Lights On");
((JButton) ev.getSource()).setActionCommand(ACTION_ON);
break;
case ACTION_CYCLE:
if (isLightOn)
getContentPane().setBackground(COLORS[++currentColor
% COLORS.length]);
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DiscoLightsExample();
}
});
}
}
on threading and swing
Finally, before moving on to the next section, there is one more important thing to highlight when
working with event listeners—and indeed with UIs in general when using Swing. Recall that when-
ever you build a GUI with Java Swing, an event loop will start running in the background that will
check for user actions and dispatch events to your listeners. To be more precise, all Swing event
handling code runs on a special thread known as the Event Dispatch Thread. We won't talk in depth
about threads in a beginner's book on programming, but in general, think about a thread as a unit
of execution in a program. For instance, the following code snippet shows how two threads are cre-
ated that will count from 1 to 10 in parallel:
 
Search WWH ::




Custom Search