在 JTree 上单击移动到可滚动 JTextArea 中的行

On JTree Click Move to Line in Scrollable JTextArea

您好,我正在尝试让我的 JTextArea 滚动到用户从 JTree 单击的行。但是,我不知道如何让 JTextArea 专注于该特定行。

例如,如果用户单击具有第 118 行信息的 JTree 节点,那么我希望 JTextArea 滚动到该行。我在下面有一张图片展示了我的意思,以及部分代码。

代码:

private static JFrame frame;
private static JLabel lblFileChosen;
private static JTextArea resultsTextArea;
private static JScrollPane scroll2;
private static JTextArea LogFileTA_1;
private static JTree errorTree;
private static DefaultTreeModel model;
private static ArrayList<logObject> rftdArrayList = new ArrayList<logObject>();


private static void clickErrorTree(MouseEvent me) 
{
    TreePath tp = errorTree.getPathForLocation(me.getX(), me.getY());
    if (tp != null)
      System.out.println(tp.toString());
    else
      System.out.println("huh");
}

private void initialize() 
{
    frame = new JFrame();
    frame.setBounds(100, 100, frameW, frameH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().setLayout(new BorderLayout(0, 0));

    LogFileTA_1 = new JTextArea(34,78);
    frame.getContentPane().add(LogFileTA_1, BorderLayout.WEST);
    LogFileTA_1.setWrapStyleWord(true);
    LogFileTA_1.setLineWrap(true);
    LogFileTA_1.setText("Log File");

    LogFileTA_1.setEditable(false);
    LogFileTA_1.setVisible(true);

    JScrollPane scroll1 = new JScrollPane(LogFileTA_1);
    frame.getContentPane().add(scroll1, BorderLayout.WEST);

    lblFileChosen = new JLabel("File Chosen: ");
    lblFileChosen.setVerticalAlignment(SwingConstants.BOTTOM);
    lblFileChosen.setHorizontalAlignment(SwingConstants.LEFT);
    frame.getContentPane().add(lblFileChosen, BorderLayout.SOUTH);

    errorTree = new JTree();
    errorTree.setVisibleRowCount(5);
    errorTree.setModel(null);

    resultsTextArea = new JTextArea();
    //resultsTextArea.setRows(8);
    resultsTextArea.setText("Results Area");
    resultsTextArea.setColumns(10);
    //frame.getContentPane().add(resultsTextArea, BorderLayout.CENTER);
    resultsTextArea.setEditable(false);


    scroll2 = new JScrollPane(errorTree);
    scroll2.setColumnHeaderView(resultsTextArea); //errorTree
    frame.getContentPane().add(scroll2, BorderLayout.CENTER);

    mntmOpen.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            errorTree.setModel(null);
            createFileChooser(frame);               
        }

    });

    errorTree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
          clickErrorTree(me);
        }
      });
}

, if the user clicks a JTree node that has information on line 118 then I want the JTextArea to scroll to that line.

查看 Text Utilities

您可以使用RXTextUtilities.gotoStartofLine(...)方法。

如果需要,您也可以使用 RXTextUtilities.centerLineInScrollPane(...) 方法。