问题描述
我想要我的 JTextPane 插入符号的 X 和 Y 位置。
这是我现在所拥有的:
WORD
此代码来自:https://stackoverflow.com/a/18864392/14911094
但是有问题!
这没问题,但我还有一个带有 JTextPane 的滚动窗格(这是 JFrame 构造函数的代码):
Rectangle2D rectangle = textPane.modelToView2D(textPane.getcaretposition());
popupMenu.show(frame,(int)rectangle.getX(),80 + (int)rectangle.getY());
editorPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(editorPane);
this.setLayout(new GridLayout(1,1,0));
this.add(scrollPane);
所以当我下线时,弹出窗口会移出屏幕,因为 rectangle.getY() 非常高。
我该如何解决这个问题!
这是一个最小的可重现示例:
popupMenu.removeAll();
for (String item : stringItems)
popupMenu.add(new JMenuItem(item));
Rectangle2D rectangle = editorPane.modelToView2D(editorPane.getcaretposition());`
popupMenu.show(frame,80 + (int)rectangle.getY());
popupMenu.updateUI();
解决方法
https://stackoverflow.com/users/131872/camickr 建议的答案是评论!
我的代码的问题是我显示的是关于框架而不是文本窗格的弹出菜单
这是一个解决方案。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.util.*;
public class Try {
public static final int CARET_HEIGHT = 15;
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
JTextPane textPane = new JTextPane();
JScrollPane pane = new JScrollPane(textPane);
JPopupMenu popupMenu = new JPopupMenu();
textPane.setText("SOME RANDOME TEXT FHDFFHNGHNFKJ!");
textPane.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
try {
Rectangle2D rectangle = ((JTextPane)(e.getSource())).modelToView2D(textPane.getCaretPosition());
popupMenu.show(((JTextPane)(e.getSource())),(int) rectangle.getX(),CARET_HEIGHT + (int) rectangle.getY());
} catch (Exception ex) {}
frame.requestFocus();
frame.requestFocusInWindow();
textPane.requestFocusInWindow();
}
});
String itms[] = {
"HI","Hello"
};
ArrayList < String > items = new ArrayList < > (Arrays.asList(itms));
for (String item: items)
popupMenu.add(new JMenuItem(item));
frame.add(pane);
frame.setSize(900,500);
frame.setVisible(true);
}
}