2011-12-30 95 views
3

我使用Java创建便笺应用程序。使用JButton增加/减少textArea内的字体大小

我想做什么: 我想我每次点击增加尺寸增加内部textArea文本的大小。 我会知道如何做相反的显然。

短代码:

 JButton incButton = new JButton("+"); 
     fontFrame.add(incButton); 
     incButton.addActionListener(new fontIncAction()); 
     JButton DecButton = new JButton("-"); 
     fontFrame.add(DecButton); 

     //textArea.setFont(Font("Serif", Font.PLAIN, fz)); 
    } 
} 

private class fontIncAction implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 

     textArea.setFont(new Font("Serif",Font.PLAIN,20)); 
    } 
} 
+0

这纯粹是一种猜测,但尝试:文本.setText(textArea.getText())更改字体后。所有应该做的就是重置文本。我的直觉是,改变字体只适用于框中的新文字。如果这不起作用,我不能帮你。我只是觉得猜测比沉默更好:)祝你好运! – 2011-12-30 01:00:08

+0

1)使用字体的当前大小作为新大小的基础。 2)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 3)你在实现目标时遇到了什么确切的问题? – 2011-12-30 01:04:12

+0

@CodyS,该字体适用于整个文本。您不必更换文字。 – camickr 2011-12-30 01:04:44

回答

8

为了使代码更一般的,你可以做这样的事情在你的ActionListener如下:

Font font = textArea.getFont(); 
float size = font.getSize() + 1.0f; 
textArea.setFont(font.deriveFont(size)); 
+0

哇!从来没有见过这样的事情! '1.0f'中的'f'究竟是什么?'deriveFont'是什么?所以'getSize()'返回字体的大小。 – Sobiaholic 2011-12-30 01:12:58

+1

@iMohammad:另见[§3.10.2浮点文字](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.2)。 – trashgod 2011-12-30 01:24:07