Reputation: 55
I have a JToolBar
and a JTextPane
. On the toolbar I have buttons for bolding, underlining, etc. I tried to add a button that, when pressed, would increase the size of the text.
This code appears at the start of my ToolBar class, and is set equal to an int from my Display class where it has a default value of 24. It's used to set the original font size.
static int size = Display.size;
This code is in my ToolBar() Constructor.
final JButton reduceButton = new JButton(new ImageIcon("res/reduce.png"));
reduceButton.setToolTipText("Reduce Text...");
reduceButton.setFocusable(false);
reduceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
size -= 4;
System.out.println("FontSize = " + size);
}
});
reduceButton.addActionListener(new StyledEditorKit.FontSizeAction("myaction-", size));
For some reason the button doesn't work, however if I change the code to:
reduceButton.addActionListener(new StyledEditorKit.FontSizeAction("myaction-", 40));
..then it works. Any idea why this is?
Upvotes: 0
Views: 856
Reputation: 27326
The problem is that the size is fixed by the second invocation of addActionListener
- whatever the value of size
when that code is initially run is what it will remain.
If you need to dynamically change the font size, as you do, then you'll need to do it within your earlier action listener. Try something like
reduceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
size -= 4;
System.out.println("FontSize = " + size);
// Font has changed, instantiate a new FontSizeAction and execute it immediately.
new StyledEditorKit.FontSizeAction("myaction-", size).actionPerformed(arg0);
}
});
This is a bit strange to create a new action object just to invoke an action; I would probably rewrite this just to modify the font on the editor object directly.
As an aside, it's generally a bad idea to have static, mutable variables like this.
It looks like you can override the font size you specify in constructor via the actionCommand string in the actionEvent; see http://opensourcejavaphp.net/java/harmony/javax/swing/text/StyledEditorKit.java.html
public void actionPerformed(final ActionEvent event) {
Object newValue = null;
if (event != null) {
try {
newValue = new Integer(event.getActionCommand());
} catch (NumberFormatException e) {
}
}
performAction(event, StyleConstants.FontSize, null, defaultValue,
newValue, false);
}
But what I posted in first place should work. If it doesn't let me know what the problem is and I'll take another look.
Upvotes: 2