我有一个类UITextPane
,它扩展了JTextPane
,并重写了paintComponent(g)
方法,如下所示:
package com.ritcat14.GotYourSix.graphics.UI;
import com.ritcat14.GotYourSix.util.ImageUtil;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JTextPane;
public class UITextPane extends JTextPane {
private BufferedImage img;
public UITextPane() {
img = ImageUtil.getImage("/ui/panels/helpBackground.png");
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(img,0,0,null);
super.paintComponent(g);
}
}
然后在我的 Game.java
类中,我使用 GridBagConstraints
创建组件并将其添加到 JFrame,如下所示:
game.textPane = new UITextPane();
game.textPane.setEditable(false);
game.textPane.setForeground(new Color(0xffC20F1B));
game.textPane.setBackground(new Color(1,1,1, (float) 0.01)); //Set transparent so we can see the text
//create and set font
....
JScrollPane sp = new JScrollPane(game.textPane);
sp.setPreferredSize(new Dimension(400,400));
c.anchor = GridBagConstraints.LINE_END;
game.frame.add(sp, c);
每次调用游戏的渲染方法时都会调用 textPane.paintComponent(g)
。
我的问题:我存储的图像只是一个 400x400
透明图像,我将其绘制到 UITextPane
类中的 JTextPane
中。但是,结果如下所示:
唱歌后,背景变黑,如下所示:
你知道我做错/没做什么吗?谢谢
最佳答案
一些 LaF 不尊重背景属性(property)。无论如何,你应该使用 setOpaque 来实现你想要的。
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame mainFrame = new JFrame("test");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Opaque (default behaviour)
Container pane = mainFrame.getContentPane();
JTextPane jtp1 = new JTextPane();
jtp1.setOpaque(true);
jtp1.setText("this JTextPane is not transparent");
jtp1.setEditable(false);
//Not opaque (ie transparent)
JTextPane jtp2 = new JTextPane();
jtp2.setOpaque(false);
jtp2.setText("this JTextPane is transparent");
jtp2.setEditable(false);
pane.setLayout(new FlowLayout());
pane.setBackground(Color.LIGHT_GRAY);
pane.add(jtp1);
pane.add(jtp2);
mainFrame.pack();
mainFrame.setVisible(true);
}
});
}
关于Java:JTextPane 加载不透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34251341/