java - setFont() 问题

标签 java swing fonts actionlistener jtogglebutton

我有两个按钮来编辑文本中的字体。粗体按钮和斜体按钮,单独使用时效果很好,但组合在一起时效果不佳。如何让按钮协同工作? (粗体+斜体)

final JToggleButton boldbuttonpage1 = new JToggleButton("");
        boldbuttonpage1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(boldbuttonpage1.isSelected()){
                    textpage1.setFont(new Font("Arial", Font.BOLD, 12));
                }
                else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
            }
        });
        boldbuttonpage1.setBounds(21, 32, 27, 23);
        gtapage1.add(boldbuttonpage1);

        final JToggleButton italicbuttonpage1 = new JToggleButton("");
        italicbuttonpage1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(italicbuttonpage1.isSelected()){
                    textpage1.setFont(new Font("Arial", Font.ITALIC, 12));
                }
                else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
            }
        });
        italicbuttonpage1.setBounds(21, 93, 27, 23);
        gtapage1.add(italicbuttonpage1);

最佳答案

当您通过一个按钮设置字体时,您会覆盖之前的字体,从而消除之前按下按钮可能产生的任何影响。我自己会让两个 ActionListener(或 ItemListener)调用相同的方法,该方法检查两个按钮的状态并根据按钮值设置相应的字体。

此外,根据我的评论,摆脱 Eclipse 标签,而是在您的问题中添加 Swing 标签,这样就不会误导任何人。 Eclipse 只是您用作 IDE 的工具,与您的问题无关。

顺便说一句,您不应该设置组件的边界或使用空布局,而应该使用正确的布局管理器。

<小时/>

编辑
你问:

A method to check the state of the buttons? Can you elaborate that please?

您已经知道如何通过调用 isSelected() 方法来检查按钮的状态。按下按钮时,不要只检查一个按钮,而是同时检查两个按钮。事实上,您可以为两个按钮提供相同的 ActionListener:

ActionListener actionListener = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // check selected states of both button one and two and set font accordingly
    // you can use if (foo && bar) {...}
    // else if (foo) {...}
    // else if (bar) {...}
    // else {.. default...}
  }
};
button1.addActionListener(actionListener);
button2.addActionListener(actionListener);

关于java - setFont() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957079/

相关文章:

css - 字体文件夹未正确链接

java - Scala 是否像 Java8 一样具有中间/终端操作?

java - paintComponent 有时只调用

html - 如何找到特定大小的特定字体的ex值

java - 如何用 JPanel 填充 JFrame 窗口?

Java:文本字段 FocusListener focusGained 执行两次,为什么?

pdf - PDF 文件通常使用 "correct"字符代码作为字体字形吗?

java - JdbcTemplate映射器空值

java - 使用嵌套 for 循环绘制圣诞树

java - 如何围绕未正确发布的值展示竞争条件?