質問

私はJTextareaにライン番号を追加しようとしていますが、いくつかの困難があります。行番号は表示されますが、適切にスクロールしません。

データの行(ログメッセージ)とそれに関連する行番号を保存するカスタムクラスのリンクリストと、テキスト領域に表示されるかどうかの可視性があります。それで、私がしたことは、2つのJTextareasを作成することでした... 1つはログを保存し、もう1つはライン番号を保存することでした。

レイアウトは機能し、ライン番号はログに正しく入力されます。問題は、私が上下にスクロールしようとするときです。ログはスクロールすると適切に調整されますが、行番号は適切に調整されません。最初に示されている最初の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を使用して両方の列を表示することです。 2つのテキスト領域を使用することは、実際には最良の解決策ではありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top