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?
The problem is that the size is fixed by the second invocation of
addActionListener– whatever the value ofsizewhen 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
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
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.