Having a problem getting my ActionListeners, Handlers, and GUI to communicate
So I am trying to get my GUI to work. When I run the code below, it does nothing, and I'm sure I'm probably just doing something dumb, but I am completely stuck...
public void actionPerformed(ActionEvent e){
UI.getIn开发者_StackOverflow社区stance().sS++;
if((UI.getInstance().sS %2) != 0){
UI.getInstance().startStop.setName("STOP");
UI.getInstance().change.setEnabled(false);
}else if(UI.getInstance().sS%2 == 0){
UI.getInstance().startStop.setName("START");
UI.getInstance().change.setEnabled(true);
}
}
public void setStartListener(StartHandler e){
this.startStop.addActionListener(e);
}
sS is an int that increments every time the button startStop is clicked. change is also a button.
not really an answer, but I think your code would be simpler if you used a boolean instead of an int, something like:
public void actionPerformed(ActionEvent e){
final boolean isEnabled = UI.getInstance().change.isEnabled();
if(isEnabled){
UI.getInstance().startStop.setName("STOP");
}else{
UI.getInstance().startStop.setName("START");
}
UI.getInstance().change.setEnabled(!isEnabled);
}
Here's an example that shows a different approach to managing a Start/Stop
button. It uses an instance of javax.swing.Timer
to pace updates. Encapsulating the control button and display label may simplify maintenance. This variation illustrates adding a third command to pause updates.
private static final String Start = "Start";
private static final String Stop = "Stop";
…
private static void create() {
…
final JButton button = new JButton(Stop);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (Stop.equals(cmd)) {
jtl.stop();
button.setText(Start);
} else {
jtl.start();
button.setText(Stop);
}
}
});
…
}
More generally, use Action
to encapsulate functionality for use elsewhere in your program. This example "exports several actions that make it easy to use them in a control panel."
精彩评论