gpt4 book ai didi

java - JScrollPane 中 JTextPane 文本后面的静态图像

转载 作者:行者123 更新时间:2023-12-02 02:05:48 24 4
gpt4 key购买 nike

所以我有一个 JScrollPane,我需要滚动(仅垂直)居中的自动换行文本。文本后面应该是静态的、不可滚动的部分透明图像。

我的第一个方法是将图像添加到 JScrollPane 中的 JTextPane 中。由于强制图像滚动到其存在的位置之外,因此失败。

我的第二种方法是使 JTextPane 的背景透明并在 JLabel 上显示 JTextPane 后面的图像。由于 JTextPane 的后台在 JScrollPane 中无法透明,因此此操作失败。- 现在我可以使其透明,但它会留下损坏的、颜色错误的和错位的文本以及随机出现在 JTextPane 上的滚动条。

我的第三种方法是使用 JTextArea 并在其后面显示图像。由于 JTextArea 无法使文本居中,此操作失败。

我的第四种方法是使用 JLabel 来显示文本。由于 JLabel 无法自动换行,此操作失败。尽管有些人似乎对此进行了 html 修复,但没有一个起作用,因为它们都包裹在错误的位置。

所以我不确定下一步应该尝试什么,非常感谢任何帮助。

最佳答案

My second approach was to make the JTextPane's background transparent

是的,这是查看任何背景图像所必需的

Behind the text should be a static, non-scrollable partially transparent image.

您想要对滚动 Pane 的 JViewport 进行自定义绘制以显示图像。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class ViewportBackground
{
private static void createAndShowUI()
{
JTextArea textArea = new JTextArea(10, 30);
// JTextPane textArea = new JTextPane();
textArea.setOpaque(false);

Image image = new ImageIcon("mong.jpg").getImage();

JViewport viewport = new JViewport()
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);

// add custom painting here.
// For a scaled image you can use:

g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
};

JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewport(viewport);
scrollPane.setViewportView( textArea );

JFrame frame = new JFrame("Viewport Background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( scrollPane );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

关于java - JScrollPane 中 JTextPane 文本后面的静态图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68474883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com