2011-12-30 93 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