我正在编写的程序中有一个透明的、可编辑的 JTextPane(以允许显示背景),除了文本插入符之外,一切都运行良好。
插入符号本身行为正常,但每次绘制时,它都会破坏其后面区域的透明度,如图所示:
有什么方法可以使插入符号的背景透明而不需要重新绘制整个框架? DefaultCaret
没有 setOpaque()
方法,所以我不太确定如何解决这个问题。
谢谢!
编辑:我还不能回答我自己的问题,但我最终编写了一个完美运行的 SSCCE,所以我的程序肯定还有其他问题。为了供将来引用,这是我编写的(工作)代码:
import java.awt.*;
import javax.swing.*;
class TransparentScrollPane extends JScrollPane {
public TransparentScrollPane(Component view) {
super(view);
this.setPreferredSize(new Dimension(540,480));
this.setOpaque(false);
this.viewport.setOpaque(false);
this.setBorder(null);
}
}
public class TextPaneExample extends JTextPane {
public TextPaneExample()
{
super();
this.setOpaque(false);
}
public void paintComponent(Graphics g)
{
g.setColor(new Color(255,255,255,128));
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(640, 480);
JPanel panel = new JPanel();
panel.setBackground(new Color(255,128,255));
TextPaneExample textPane = new TextPaneExample();
TransparentScrollPane scroller = new
TransparentScrollPane(textPane);
textPane.setBackground(new Color(255,255,255,128));
frame.add(panel);
panel.add(scroller,BorderLayout.CENTER);
frame.setVisible(true);
}
}
最佳答案
参见Backgrounds With Transparency对于这个问题和一些解决方案。
基本上你可以使用:
panel.add( new AlphaContainer(componentWithTransparency) );
对于您的第一个问题,您将获得一个免费答案:) future 的问题应包含一个正确的 SSCCE
来演示问题。
关于java - 透明 JTextPane 中的插入符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20223743/