我有一個Java代碼,在那裏我實現了一個半透明的JPanel,並在其上用Graphics 2D繪製了一個圖像。此圖片是一個PNG,包含一個白色矩形,80%不透明,遍佈JFrame。現在我需要添加一個JTextPane來顯示數據(我將它設置爲使用應用程序包中的自定義字體),但是我無法設法讓它變成半透明:它的白色背景是不透明的(即使使用textPane.setOpaque(false);
設置)和使我的JFrame的透明度有點無用......很不爽。在透明的JFrame上移除JTextPane的沒有setOpaque()的白色背景
所以我正在尋找一種方法來消除這個讓我感到困惑的白色背景。
我翻了很多谷歌搜索,但我發現的一切都是一個布爾值來設置JTextPane的不透明度。我還發現,使用圖形2D,我可以創建一個自定義的JTextPane並覆蓋它的背景,但它沒有工作......我已經嘗試了所有這些。
public class MyWindow extends JFrame {
private static class MyTextPane extends JTextPane {
public MyTextPane() {
super();
setText("Hello World");
setOpaque(false);
setBackground(new Color(0,0,0,0));
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
public static void main(String[] args) {
MyTextPane textPane = new MyTextPane();
JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
try {
Image img = ImageIO.read(new File("images/bg.png"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
} catch (IOException e) {
e.printStackTrace();
}
if (g instanceof Graphics2D) {
final int R = 240;
final int G = 240;
final int B = 240;
Paint p =
new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
0.0f, getHeight(), new Color(R, G, B, 0), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
};
panel.add(textPane);
setContentPane(panel);
}
(產地與Oracle的解釋JFrame中透亮,就在這裏HERE)謝謝!
你添加文本窗格滾動窗格? – MadProgrammer
不,我將它添加到'Jpanel panel = new JPanel();'。我要編輯我的帖子:) – guillaume
什麼是MyTestPane? – MadProgrammer