gpt4 book ai didi

java - 在具体的地方使用 JTextPane 进行绘制

转载 作者:行者123 更新时间:2023-12-01 11:18:13 24 4
gpt4 key购买 nike

假设我们有一个 JTextPane,其大小设置为 A4 纸张格式大小。页面方向是垂直的。让我们将页面分成三个相等的部分。当我在一个部分(随机位置)写一些内容时,我希望插入的文本将绘制在页面的两个剩余部分上,这样如果我将页面折叠成三个,所有三个文本都将位于同一个位置。有什么办法可以实现这一点吗?

这应该看起来像这样: /image/mNJDl.png

最佳答案

我不确定我理解你想要什么,所以如果我误解了,请纠正我。您可以在显示时保存文本 Pane 的图像,并根据需要绘制恢复或正常的图像。见下文:

public class Test {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame mainFrame = new JFrame("test");
mainFrame.setSize(300, 100);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//layout to make every part the same size
Container pane = mainFrame.getContentPane();
pane.setLayout(new GridLayout(3,1));

//create the elements
JTextPane source = new Source();
final JPanel copy = new Copy();
final JPanel revertedCopy = new RevertedCopy();

//add the elements
pane.add(source);
pane.add(revertedCopy);
pane.add(copy);

//This is just to display the splitting lines
source.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));

//this is just to repaint the other panels when image changes
source.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("drawing")) {
copy.repaint();
revertedCopy.repaint();
}
}
});

mainFrame.setVisible(true);
}
});
}

static BufferedImage image;
static class Source extends JTextPane {
@Override
public void paint(Graphics g) {
super.paint(g);
//we edit the image each time the textPane is repainted
image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
boolean caretVisible = getCaret().isVisible(), selectionVisible = getCaret().isSelectionVisible();
if(caretVisible) getCaret().setVisible(false);
if(selectionVisible) getCaret().setSelectionVisible(false);
super.paint(image.createGraphics());
if(caretVisible) getCaret().setVisible(true);
if(selectionVisible) getCaret().setSelectionVisible(true);

//we let the copies know about the changes
firePropertyChange("drawing", null, image);
}
}
static class Copy extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
//we just draw the image
if(image!=null) g.drawImage(image, 0, 0, this);
}
}
static class RevertedCopy extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
//we just draw the image reverted
if(image!=null) g.drawImage(image, 0, image.getHeight(), image.getWidth(), -image.getHeight(), this);
}
}
}

关于java - 在具体的地方使用 JTextPane 进行绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31542093/

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