Modify ActionListener notification for JButton derivative, correct
approach?
Hi,
I am currently working on a GUI program that allows the user to edit
various properties of a large variety of objects.
For each property type (such as Shape, Paint, Stroke, Font etc.
objects) I would like to have an "editor" that is merely a button
which upon clicking opens a dialog box that allows the user to specify
the details of the property (such as RGB values for a Paint or Color
object and font name, style and size for a ... guess what .. a Font
object).
Here is the problem: listeners of the editor should only be notified
when the user presses "OK" in the dialog box and not when the button
is clicked! Clicking on the button should just open the dialog and do
nothing else. I have fough several hours to achieve that and dug my
way through various source codes. Here is the results as an SSCCE. It
seems to work but I am not sure whether there is something lurking in
the code. In particular, I am not sure whether the ActionEvent has
been generated in a correct way that won=B4t produce any strange errors
sooner or later. Thanks for your comments!
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
public class PropertyEditorDemoShort implements ActionListener{
PaintEditor editor = new PaintEditor("Edit paint");
public PropertyEditorDemoShort() {
JFrame frame = new JFrame("Property Editor Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.addActionListener(this);
frame.getContentPane().add(editor);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
PropertyEditorDemoShort demo = new PropertyEditorDemoShort();
}
public void actionPerformed(ActionEvent ae){
System.out.println("Action performed by "+ae.getSource());
}
}
class PaintEditor extends JButton{
private ButtonModel model = new DefaultButtonModel();
private Paint paint = new Color(128,128,128);
private MouseAdapter mouser = new MouseAdapter(){
public void mouseClicked(MouseEvent me){
showPanel();
}
};
public PaintEditor(String label){
super(label);
addMouseListener(mouser);
}
public Paint getpaint(){
//to be called from action listeners when the user is finished
editing
return paint;
}
protected void showPanel(){
int value = JOptionPane.showConfirmDialog(null, getPanel(),"Edit
Properties",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
if(value == JOptionPane.OK_OPTION){
fireActionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand()));
}
}
private JPanel getPanel(){
JPanel panel = new JPanel();
panel.add(new JLabel("Please fine tune color properties here"));
return panel;
}
public ButtonModel getModel(){
return model;
}
}