Reputation: 7271
This is my first time doing gui programming with java swing n co so I need some advice. I am currently adding functionality to buttons by setting action commands on the buttons. I then listen on the container for actions like below:
colorButton.setText("Select Color");
colorButton.setFocusable(false);
colorButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
colorButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(colorButton);
jToolBar1.add(jSeparator1);
colorButton.setActionCommand("selectColor");
colorButton.addActionListener(this);
I then check for which component a performed action was performed on using snippet like below:
else if("selectColor".equals(e.getActionCommand())) {
Color c = JColorChooser.showDialog(this, "Select Color", Color.GREEN);
if (selectedShape != null) {
undoStack.add(copyOf(model.getAllShapes()));
model.setShapeColor(selectedShape, c);
}
else{
defaultColor = c;
}
}
I just want to know if this is good or bad practice?
Upvotes: 1
Views: 2940
Reputation: 116137
What I would usually do is use an anonymous class, e.g.
JButton button = new JButton("BUTTON");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event ) {
// do relevant stuff
}
});
EDIT: MadProgrammer's comment (above) sums up your options nicely. This might indeed not be the best approach for 'longer' methods, but for simple ones it's nice and clear imho.
Upvotes: 1