1
如何計算px中字符串的寬度?我有面板,我嘗試像(此參考JPanel)如何計算px中字符串的寬度?
FontMetrics gp = this.getGraphics().getFontMetrics();
int x=gp.stringWidth("test");
但getGraphics返回始終爲空,因爲面板不可見。如何解決這個問題呢 ?
如何計算px中字符串的寬度?我有面板,我嘗試像(此參考JPanel)如何計算px中字符串的寬度?
FontMetrics gp = this.getGraphics().getFontMetrics();
int x=gp.stringWidth("test");
但getGraphics返回始終爲空,因爲面板不可見。如何解決這個問題呢 ?
您應該在存在Graphics
實例的paint()
或paintComponent()
方法之一中執行此操作。您可以創建一個BufferedImage
並致電getGraphics()
。
忘記方法component.getGraphics() - 你不需要它:要麼你已經有了一個Graphics對象(作爲參數傳入,在paintComponent中是fi),或者你不應該使用它;-) – kleopatra 2011-04-21 06:37:54