1

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?

3
  • This is very similar to what I do except I use "e.getSource()" and compare to the button. However, I have my listeners in anonymous inner classes. I am not sure if this is a better/worse practice. Commented Nov 7, 2012 at 23:34
  • 5
    There is nothing particularly wrong with the approach (it's how it was designed to work), however, I'd suggest having a read through How to Use Actions, it's little more advanced, but the concept is the same. As Bucco suggests, you might want to seperate your ActionListeners either into groups (some they deal with a single concept of actions) or use inner classes. I would discourage the use anonymous classes if the body of the listeners exceeds a dozen or so lines, as they become difficult to read Commented Nov 7, 2012 at 23:43
  • Also see this question Commented Nov 8, 2012 at 7:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.