1

我正在尝试将行号添加到 JTextArea 并且遇到了一些困难。行号出现,但不能正确滚动。

我有一个自定义类的链表,它存储一行数据(日志消息)和与之关联的行号,以及是否应该在文本区域中显示它的可见性。所以我所做的是创建两个 JTextAreas... 一个用于存储日志,另一个用于存储行号。

布局有效,行号正确填充日志。问题是当我尝试向上或向下滚动时。滚动时日志会正确调整,但行号不会。除了最初显示的最初的 28 行号之外,什么也没有显示。空间只是空白。

我的代码如下:

public class CustomLineNumbers extends JFrame implements ActionListener
{    
    ...
    private JTextArea logField;
    private JTextArea lineField;

    private List<Log> logs;

    public CustomLineNumbers() 
    {       
        ...
        logs = new ArrayList<Log>();

        logField = new JTextArea(28, 68);
        logField.setMargin(new Insets(0, 5, 0, 0));
        logField.setEditable(false);
        logField.setLineWrap(true);
        logField.setWrapStyleWord(true);

        lineField = new JTextArea();
        lineField.setPreferredSize(new Dimension(25, 0));
        lineField.setBackground(this.getForeground());
        lineField.setBorder(OUTER);
        lineField.setEditable(false);

        initLogs();
        updateLogView();
        updateLineView();

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.getViewport().add(logField);
        scrollPane.setRowHeaderView(lineField);
        scrollPane.setVertical...Policy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        ...
    }

    private void initLogs()
    {
        // inits the data in the list
    }

    public void updateLogView()
    {
        logField.setText("");   // reset log field to nothing

        for (int i = 0; i < logs.size(); i++)
        {
            // Append only if the line is visible
            if (logs.get(i).getVisibility())
            {
                // if this isn't the first line, 
                // add a line break before appending
                if (i > 0)
                    logField.append("\n");  

                logField.append(logs.get(i).getLine());
            }
        }       
    }

    public void updateLineView()
    {
        lineField.setText("");  // reset log field to nothing

        for (int i = 0; i < logs.size(); i++)
        {
            // Append only if the line is visible
            if (logs.get(i).getVisibility())
            {
                // if this isn't the first line, 
                // add a line break before appending
                if (i > 0)
                    lineField.append("\n"); 

                lineField.append("" + logs.get(i).getLineNumber());
            }
        }       
    }

    ...

    /***** Main Execution *****/
    public static void main(String[] args) { ... }
}

有任何想法吗?

谢谢,

4

2 回答 2

4

您是否尝试将两个文本字段都放在视口中?也许在一个面板上给出了可用宽度的一小部分行号?

于 2011-01-06T18:15:31.087 回答
2

可以使用以下方法添加用于显示行号的组件:

scrollPane.setRowHeaderView(...);

另一种选择是使用 JTable 来显示两列。使用两个文本区域确实不是最好的解决方案。

于 2011-01-06T19:28:48.087 回答