2017-07-31 125 views
0

我想創建一個具有半透明背景的JTextField(即具有alpha值爲120的黑色背景)。我目前的代碼是:如何使JTextField半透明

public static void designTextField(final JTextField tf) { 
     tf.setBorder(null); 
     tf.setFont(new Font("Comfortaa", Font.PLAIN, 30)); 

     tf.setBackground(new Color(0, 0, 0, 120)); 
     tf.setForeground(new Color(200, 200, 200, 200)); 
} 

但是,這似乎並沒有工作。下面是這段代碼的結果(有兩個文本字段)圖片:

未輸入文字:

No text entered

輸入的文本:

Text entered

由於你會發現有幾個奇怪的繪圖錯誤,並且這兩個文本字段似乎完全不透明。我怎樣才能解決這個問題?

+1

擺動組件通常在透明度方面效果不佳。看看https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/ – Ansharja

回答

0

擺動完美的透明度。你只需要添加

tf.setOpaque(false); 

https://docs.oracle.com/javase/tutorial/uiswing/painting/problems.html 部分「問題:視覺假象出現在我的GUI」解釋說。

+0

我已經試過這個,它會導致文本字段變得完全變白:https:// sc。 reflex.rip/PHcyfX.png – HopeIsNope

+0

要獲得半透明文本字段背景,您還需要重寫組件繪製的方式:'JTextField tf = new JTextField(){ @Override protected void paintComponent(Graphics g){ g .setColor(new Color(0,0,0,100)); (getX(),getY(),getWidth(),getHeight()); super.paintComponent(g); } };' –