java - StyledEditorKit.FontSizeAction() 无法通过 JButton 工作

标签 java swing jbutton actionlistener jtextpane

我有一个 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));

..然后就可以了。知道这是为什么吗?

最佳答案

问题在于,该大小是由第二次调用 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);
    }
});

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

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

看起来你可以通过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);
    }

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

关于java - StyledEditorKit.FontSizeAction() 无法通过 JButton 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241935/

相关文章:

java - 使用 Ping 结果动态更改 JLabel

java - 如何开始,使用几个面板开发基于 swing 的应用程序,每个面板都有下一个按钮

java - 无法打开 Alfresco admin-consle.jsp

java - jsp中无法访问jpg

java - 如何从 Java 中的另一个类获取变量?

Java:从 GUI 中删除 GUI 对象

java - mysqlexecute() 方法给出错误值,即使执行正确

java - AbstractListModel 有 getSelectedIndex() 方法吗?

java - 如何从单击按钮的代码中进行调用?

java - Netbeans 设计 View 中的动态按钮