0

我有一个JToolBar和一个JTextPane。在工具栏上,我有加粗、下划线等按钮。我尝试添加一个按钮,按下该按钮会增加文本的大小。

此代码出现在我的 ToolBar 类的开头,并设置为等于我的 Display 类中的一个 int,它的默认值为 24。它用于设置原始字体大小。

static int size = Display.size;

此代码在我的 ToolBar() 构造函数中。

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));

由于某种原因,该按钮不起作用,但是如果我将代码更改为:

reduceButton.addActionListener(new StyledEditorKit.FontSizeAction("myaction-", 40));

..然后它工作。知道这是为什么吗?

4

1 回答 1

2

问题是大小是由第二次调用固定的addActionListener- 无论该size代码最初运行时的值是什么,它将保持不变。

如果您需要动态更改字体大小,就像您所做的那样,那么您需要在之前的动作侦听器中进行。尝试类似的东西

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);
    }
});

仅仅为了调用一个动作而创建一个新的动作对象有点奇怪;我可能会重写它只是为了直接修改编辑器对象上的字体。

顺便说一句,拥有像这样的静态、可变变量通常是个坏主意。

看起来您可以通过 actionEvent 中的 actionCommand 字符串覆盖您在构造函数中指定的字体大小;见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);
    }

但是我首先发布的内容应该有效。如果它不让我知道问题是什么,我会再看看。

于 2012-09-03T06:32:38.583 回答