簡體   English   中英

不需要時顯示 JTextArea 垂直滾動條

[英]JTextArea vertical scrollbar showing up when not needed

我需要 JTextArea 中的垂直滾動條僅在需要時出現,為此我知道我需要根據需要使用垂直滾動條。 但是滾動條一直顯示,像這樣:

在此處輸入圖片說明

即使顯然不需要。 我究竟做錯了什么?

// make top panel where output from the menu selections will appear
        topP = new JPanel(new BorderLayout());
        topP.setSize(new Dimension(500,150));
        // make default text message to be displayed in top panel
        output = new JTextArea("Output printed here...", 20, 20);
        // styles the text in the textarea
        output.setForeground(Color.BLUE);
        output.setFont(new Font("Times New Roman", Font.BOLD, 20));
        topP.add(output, BorderLayout.NORTH); // add default text to the top panel
        right.add(output);

        // here's the scrollbar guys
        top = new JScrollPane(output); // applies to the textarea
        top.setPreferredSize(new Dimension(500,150));
        top.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        top.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        topP.add(top, BorderLayout.NORTH);

查看 JTextArea 的文檔 如果向下滾動到構造函數摘要部分,您將看到以下內容:

JTextArea (String text, int rows, int columns) 用指定的文本和行數和列數構造一個新的 TextArea。

這與您使用的構造函數相同:

output = new JTextArea("Output printed here...", 20, 20);

通過指定行和列,您可以有效地告訴 JTextArea 它必須具有特定大小,並且滾動窗格只是通過顯示滾動控件來響應您的規范。 這些滾動控件是根據您要求的行數和列數顯示的,而不是文本區域內的可見文本量。

如果您在不指定行和列的情況下構建 JTextArea,則不會有任何滾動條。 由於您正在設置文本區域的大小,因此無論如何指定行和列都是多余的。 只是不要這樣做。

注意:您應該避免設置 Swing 組件的絕對大小。 僅設置首選大小,當您調用pack() ,Swing 將嘗試盡可能地適應您的規范。 當您指定絕對大小時,您的 UI 在不同平台上或當用戶調整框架大小時可能看起來非常糟糕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM