[英]Make JTextPane background transparent
我創建了自己的 Label 類,它具有可復制的優點。
public class CopyableLabel extends JTextPane {
private static final long serialVersionUID = -1;
private static final Font DEFAULT_FONT;
static
{
Font font = UIManager.getFont("Label.font");
DEFAULT_FONT = (font != null) ? font: new Font("Tahoma", Font.PLAIN, 11);
}
public CopyableLabel() {
construct();
}
private void construct()
{
setContentType("text/html");
setEditable(false);
setOpaque(false);
setBackground(null);
setBorder(null);
putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
setFont(DEFAULT_FONT);
}
public CopyableLabel(String text)
{
super();
construct();
setText(text);
}
public void setFont(Font font)
{
super.setFont(font);
setMaximumSize(new Dimension(Short.MAX_VALUE,font.getSize()+4));
}
public CopyableLabel(String title, int align)
{
super();
construct();
setText(title);
StyledDocument doc = getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
switch(align)
{
case JLabel.LEFT:
StyleConstants.setAlignment(center, StyleConstants.ALIGN_LEFT);
break;
case JLabel.RIGHT:
StyleConstants.setAlignment(center, StyleConstants.ALIGN_RIGHT);
break;
}
doc.setParagraphAttributes(0, doc.getLength(), center, false);
}
問題是,使用 Nimbus Look and Feel 時,白色背景看起來很難看。 所以我尋找讓背景透明的可能性。
你有什么解決辦法嗎?
不確定這是否有幫助。 但是使用顏色,尤其是顏色構造函數 Color(r,g,b,a) ,其中 a 是控制透明度的alpha 。
因此將construct()方法更改為:
private void construct()
{
setContentType("text/html");
setEditable(false);
setOpaque(true);
backgroundColor = getBackground();
int red = backgroundColor.getRed();
int green = backgroundColor.getGreen();
int blue = backgroundColor.getBlue();
setBackground(new Color(red, green, blue, 25));
//setBackground(null);
setBorder(null);
putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
setFont(DEFAULT_FONT);
}
當我嘗試並使用上述代碼修改 JTextPane 並將其放在半透明 JFrame 上時,它對我有用。
另一種選擇是自己設置 HTML 默認值。 我從未使用過 Nimbus,但我假設他們可能正在為 HTML 渲染設置背景顏色。 在設置 nimbus L&F 內容后,您可以在應用程序初始化中的某處手動設置它,在全局范圍內使用以下內容:
HTMLEditorKit kit = new HTMLEditorKit();
StyleSheet styleSheet = kit.getStyleSheet();
Style style = styleSheet.getStyle("body");
StyleConstants.setBackground(style, new Color(0,0,0,0));
這將使 HTML 在全局范圍內默認呈現透明背景。 因此,例如,如果您將 HTML 放入 JLabel 或其他組件中,您可以使用正常的背景控制背景顏色,而不會受到 HTML 背景的干擾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.