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?

cobie
  • 7,023
  • 11
  • 38
  • 60
  • 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. – Vineet Kosaraju Nov 07 '12 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](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html), 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 – MadProgrammer Nov 07 '12 at 23:43
  • Also see [this question](http://stackoverflow.com/q/12463345/1076463) – Robin Nov 08 '12 at 07:28

1 Answers1

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.

ChristopheD
  • 112,638
  • 29
  • 165
  • 179