我正在尝试将行号添加到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) { ... }
}

有任何想法吗?

谢谢,

有帮助吗?

解决方案

您是否尝试将两个文本字段放在视口上?也许在为线路编号提供可用宽度的一小部分的面板上?

其他提示

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

scrollPane.setRowHeaderView(...);

另一个选项是使用JTable显示两个列。使用两个文本区域实际上不是最好的解决方案。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top