Thursday, December 04, 2014

Caption text disappears on JButton if Action is assigned

While implementing yet another tool helping to automate project processes I faced an issue that took some amount of time to resolve. That might be quite obviouse for those how's been dealing with s
Swing for a long time but I spent a day to find the solution out.

So I had the code to create JButton with caption like

JButton jbPerformSomeJob = new JButton("Perform Some Job");

After I had completed building my UI I ran the app and having no logic assigned to my buttons I got the result I expected to get. I had some UI controls on my JFrame including that my button with the expected caption.

So after that I added some Action to my button as anonymous class object.

jbPerformSomeJob.setAction(new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {
performCustomJob();
}
});

After I started the application again I couldn't see the caption on the button any more.

So the solution is not obvious enough as to me. It turned out that the name of the action overrides the button caption so to have my caption back I had to define separate named class like:

class PerformSomeJobAction extends AbstractAction{

public GenerateReportAction(String text) {
super(text);
}

@Override
public void actionPerformed(ActionEvent e) {
performCustomJob();
}

}

and use the following construction for my JButton

jbPerformSomeJob.setAction(new PerformSomeJobAction("Perform Some Job"));