如何使JScrollPane与JTextArea一起出现?

问题描述 投票:0回答:1

我正在尝试创建一个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);
    }
java swing jscrollpane jtextarea
1个回答
0
投票
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约束。

© www.soinside.com 2019 - 2024. All rights reserved.