[英]How to Underline a JLabel on MouseEnter
我試圖通過使用以下方式更改字體:
jLabel.setFont(new Font("Tahoma",1,20));
但是這里只有4種樣式,即Plain,Bold,Italic,Bold + Italic。
我希望它像HTML中的鏈接一樣工作,當我將鼠標指針懸停在JLabel上時,JLabel會帶有下划線。
為了澄清(或不:-)我對mKorbel的評論中引入的困惑
切勿突然創建字體:它很可能會與應用程序中的所有其他字體沖突。 取而代之的是,獲取默認值(從下面的片段中的組件實例或UIManager中獲取,都沒有關系)並派生。
對於使用屬性的推導(從mKorbel的答案中毫不客氣地加固),這就像
JLabel label = new JLabel("some text - WE ARE UNDERLINED");
MouseListener l = new MouseAdapter() {
Font original;
@Override
public void mouseEntered(MouseEvent e) {
original = e.getComponent().getFont();
Map attributes = original.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
e.getComponent().setFont(original.deriveFont(attributes));
}
@Override
public void mouseExited(MouseEvent e) {
e.getComponent().setFont(original);
}
};
label.addMouseListener(l);
JComponent content = new JPanel();
content.add(label);
content.add(new JButton("dummy focus"));
但是請注意:這還不會給您任何超鏈接功能! 因此,如果您真正想要的是Hyperlink,請考慮使用具有這種功能的成熟組件,例如SwingX項目中的 fi JXHyperlink 。 您可能要運行在其項目主目錄上引用的演示。
用於正確的MouseEvent
JLabel#setFont(new Font(attributes));
然后回來
JLabel#setFont(new Font("Serif", Font.BOLD, 16));
包裝到invokeLater
,並來自定義
final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
將此與必需的CSS一起使用,
yourLabel.setText(htmlIfy("<p style='color:#1C66AE;'>Your text here</p>"));
htmlIfy
函數在哪里
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";
public static String htmlIfy(String s) {
return HTML.concat(s).concat(HTML_END);
}
添加文本,例如鏈接使用
yourLabel.setText(HTMLTagUtil.htmlIfy(HTMLTagUtil
.linkIfy("Your Text Here")));//Forgot Password?
yourLabel.setCursor(new java.awt.Cursor(
java.awt.Cursor.HAND_CURSOR));
linkIfy
函數在哪里
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
public static String linkIfy(String s) {
return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}
if (CheckBox.isSelected()) {
Font font = CheckBox.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_GRAY);
CheckBox.setFont(font.deriveFont(attributes));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.