Java JScrollPane以后如何设置插入符号
我有一个应用程序,需要存储当前插入符号位置,然后在滚动窗格上重新创建数据,然后将用户放回他所看到的点Java JScrollPane以后如何设置插入符号,java,swing,jscrollpane,caret,Java,Swing,Jscrollpane,Caret,我有一个应用程序,需要存储当前插入符号位置,然后在滚动窗格上重新创建数据,然后将用户放回他所看到的点 int scrollIndex = 0; if(scrollPane != null) { scrollIndex = scrollPane.getVerticalScrollBar().getValue(); } scrollPane = new JScrollPane(newpanel); scrollPane.getVerticalScrollBar().setValue(sc
int scrollIndex = 0;
if(scrollPane != null) {
scrollIndex = scrollPane.getVerticalScrollBar().getValue();
}
scrollPane = new JScrollPane(newpanel);
scrollPane.getVerticalScrollBar().setValue(scrollIndex);
这并没有将插入符号设置在上一个滚动条上,而是设置在其他一些我不理解的值上
我还寻找了getCaret,但它似乎不存在
编辑1
这几乎奏效了:
int scrollIndex = 0;
JViewport vp = null;
if(scrollPane != null) {
//scrollIndex = scrollPane.getVerticalScrollBar().getValue();
vp = scrollPane.getViewport();
}
scrollPane = new JScrollPane(newpanel);
//scrollPane.getVerticalScrollBar().setValue(scrollIndex);
scrollPane.setViewport(vp);
“视图”在我看到的滚动点保持不变。但是滚动条设置为0,即使视图正常。如果我像以前一样尝试设置值,我会再次得到错误的视图
当我执行scrollPane.setViewport(vp)时;我还需要做些什么才能使滚动条保持在原来的位置?方法
scrollPane.getVerticalScrollBar().getValue()
和scrollPane.getVerticalScrollBar().setValue(scrollIndex)代码>工作正常,使用singleJScrollPane
试试
我认为您在创建JScrollPane
的新实例时遇到了问题
而不是scrollPane=newjscrollpane(newpanel)代码>使用
scrollPane.getViewport().setView(newpanel)代码>,帮助您在视口中更改组件以进行滚动,而无需新实例
请看下一个代码示例:
public class Example extends JFrame {
private JScrollPane pane;
private int value;
public Example() {
final JTextArea jTextArea = new JTextArea(10, 10);
final JTextArea jTextArea2 = new JTextArea(10, 10);
jTextArea2.setText("1\n21\n2\n\n\n\n\n121221\ne\n\nee\ne\n");
pane = new JScrollPane(jTextArea);
JButton save = new JButton("save");
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
value = pane.getVerticalScrollBar().getValue();
}
});
JButton load = new JButton("load");
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
pane.getViewport().setView(jTextArea2);
pane.getVerticalScrollBar().setValue(value);
}
});
getContentPane().add(save,BorderLayout.WEST);
getContentPane().add(pane,BorderLayout.CENTER);
getContentPane().add(load,BorderLayout.EAST);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Example().setVisible(true);
}
});
}
}
JScrollPane如何在以后设置插入符号
!=使用JViewport
移动,但是使用get/setCaret(position)
或???@mKorbel移动对不起,我不明白你的意思?Caret是关于jTextComponents中的光标position,我明白了。你是说这与这里无关吗?如果是这样的话,你建议我用什么把滚动条旋钮放回原来的位置?原因是什么…,因为你的代码和描述中没有明确我的意思,这个逻辑是如何进行的,否则,要从JScrollPane获取JScrollBar position,如@alex2410I在此处发布的代码所示,我首先尝试使用setViewPort,而不是仅仅使用setView,但出现了一个错误。现在我已经修好了,它工作得很好。非常感谢