簡體   English   中英

如何使 JScrollPane 與 JTextArea 一起出現?

[英]How do I make JScrollPane appear with JTextArea?

我正在嘗試制作一個 UI 來查看存儲在計算機上的食譜中的食譜。 此選項卡的一部分是一個 JScrollPanel,它存儲一個顯示可用配方的 JTextArea。 所有被調用的函數都按預期工作(例如 allRecipes() 正確返回可用食譜的字符串); 但是,滾動窗格本身不會出現。 它被添加到框架中,正如我可以通過窗格所在的小灰色塊看到的那樣,但它沒有按應有的方式填充。 代碼如下:

//First panel, buttons to limit displayed recipes
    JPanel pane1 = new JPanel();
    JButton all = new JButton("All");
    JButton makeable = new JButton("Makeable");
    JTextField search = new JTextField("", 10);
    JButton searchButton = new JButton("Search Ingredient");

    //Second panel, display of recipes
    JPanel pane2 = new JPanel();
    JTextArea recipes = new JTextArea(allRecipes());
    JLabel list = new JLabel("List of Recipes:");
    JScrollPane scroll = new JScrollPane(recipes);

    //Third panel, options to add recipe and view specific recipe
    JPanel pane3 = new JPanel();
    JButton add = new JButton("Add Recipe");
    JTextField view = new JTextField("", 10);
    JButton viewButton = new JButton("View Recipe");

    //Central method
    public Recipes() {

        //basic UI stuff
        super("Recipes");
        setSize(475,350);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        setLayout(flo);

        //add pane 1
        pane1.add(all);
        pane1.add(makeable);
        pane1.add(search);
        pane1.add(searchButton);
        pane1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        add(pane1);

        //add pane 2
        pane2.add(list);
        scroll.setPreferredSize(new Dimension(10,15));
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pane2.add(scroll, BorderLayout.CENTER);
        pane2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        add(pane2);

        //add pane 3
        pane3.add(add);
        pane3.add(view);
        pane3.add(viewButton);
        add(pane3);

        //start up the UI
        setVisible(true);
    }
JTextArea recipes = new JTextArea(allRecipes());

我們不知道allRecipes()做了什么,但我猜它設置了文本區域的文本。

相反,您應該使用您希望的行/列來定義您的文本區域。 就像是:

JTextArea recipes = new JTextArea(5, 30);

然后在構造函數中添加文本:

recipes.setText( allRecipes() );

您不應該嘗試設置滾動窗格的首選大小。 首選大小將根據文本區域的首選大小自動確定,該首選大小是根據構造函數中提供的行/列計算的。

//scroll.setPreferredSize(new Dimension(10,15));

此外,組件的首選大小以像素為單位指定,以上沒有任何意義。

pane2.add(scroll, BorderLayout.CENTER); 

JPanel 的默認布局管理器是 FlowLayout。 所以在添加組件時不能只使用 BorderLayout 約束。

暫無
暫無

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

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