This is for a Java Swing JToolBar:
I have my own Toolbar class that extends JToolBar, which has buttons on it with ActionListeners. Code:
class ToolBar extends JToolBar {
JButton save, reset;
ToolBar() {
setFloatable(false);
setRollover(true);
makeButtons();
}
makeButtons() {
save = new JButton();
// Icon and tooltip code
save.addActionListener(new ButtonListener());
add(save);
reset = new JButton();
// Icon and tooltip code
reset.addActionListener(new ButtonListener());
add(reset);
protected class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
Then I've made a few other subclasses of this one because I have need for multiple toolbars for multiple frames, each having a different "save" or "reset" source/target. I'll just give one for simplicity:
class FullToolBar extends ToolBar {
protected class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == save) FullInput.save();
else if (event.getSource() == reset) FullInput.reset();
}
}
}
FullInput is the name of one of my JFrame's which the toolbar will go on. It has both a save and reset method which are static, but for some reason when I add the FullToolBar to my FullInput the buttons don't work.
Am I misunderstanding that nested classes can be inherited and overriden? Any ideas/comments or even suggestions of a completely different way to do what I'm trying to accomplish here? Basically, need a way to use the save and reset button on different frames/classes with the same toolbar.
No, you can't override a nested class like that. there are a couple of ways you can tackle this. one would be to put the overrideable method on the main Toolbar class, e.g.:
class ToolBar extends JToolBar {
makeButtons() {
save = new JButton();
// Icon and tooltip code
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
saveButtonPressed(event);
}
});
}
protected void saveButtonPressed(ActionEvent event) {}
}
Then, a subclass can customize the action when the save button is pressed by overriding the saveButtonPressed
method.