2009-12-02 124 views

回答

17

創建一個新的Font對象。

Display display = new Display(); 
Shell shell = new Shell(display); 
shell.setLayout(new GridLayout()); 
Label label = new Label(shell, SWT.NONE); 
label.setText("I am italic"); 
FontData fontData = label.getFont().getFontData()[0]; 
Font font = new Font(display, new FontData(fontData.getName(), fontData 
    .getHeight(), SWT.ITALIC)); 
label.setFont(font); 
shell.open(); 
while (!shell.isDisposed()) { 
    if (!display.readAndDispatch()) 
    display.sleep(); 
} 
font.dispose(); 
display.dispose(); 
+8

這是很荒謬的,但它的工作原理。謝謝! – 2011-09-27 14:36:29

+3

只是想,人們說Java太冗長了 – 2015-04-01 17:09:02

15

這將是更好地使用FontRegistry類從JFaces,像這樣:

label.setFont(
    JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT) 
); 
+1

應該指出的是,這個輔助類將自動處理所有請求的字體。所以你不再需要繼續引用它們,除了這個解決方案的簡潔之外,這是一個不錯的獎勵。 – JBert 2014-11-03 15:13:50

+2

只是一個小的更正:當使用空字符串實現相同的效果時,獲得默認斜體字體的「正確」方式是'getItalic(JFaceResources.DEFAULT_FONT)' – 2015-04-30 15:28:49

+0

編輯,謝謝。 – Esteve 2015-08-19 10:28:16

1

一個recent article(2014年2月從Jordi Böhme López)提出另一種方式來獲得當前字體,以便修改:

這就像獲取默認字體的藍圖,進行一些修改並用修改後的藍圖構建新字體:

Label label = new Label(parent, SWT.NONE); 
FontDescriptor descriptor = FontDescriptor.createFrom(label.getFont()); 
// setStyle method returns a new font descriptor for the given style 
descriptor = descriptor.setStyle(SWT.BOLD); 
label.setFont(descriptor.createFont(label.getDisplay)); 
label.setText("Bold Label"); 
+0

它似乎你必須做一些像描述符= descriptor.setStyle(SWT.BOLD);這更像是一個create()而不是set()方法 – 2014-03-11 14:15:45

+0

該解決方案不幸1:1不能正常工作。無法找到修復程序。 – mvreijn 2014-06-16 11:18:25

+0

setStyle方法返回給定樣式的新字體描述符,所以更好的描述符= descriptor.setStyle(SWT.BOLD)例如 – benez 2015-11-23 23:57:02

0

下面的代碼應該工作:

Label lblSample = new Label(shell, SWT.BORDER_SOLID); 
lblSample.setFont(new org.eclipse.swt.graphics.Font(null, "Times New Roman", 12, SWT.BOLD | SWT.ITALIC)); 
lblSample.setText("Enter Text Here");