【发布时间】:2020-05-27 05:18:38
【问题描述】:
我正在尝试制作一个 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);
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 顺便说一句 - 这只是一个猜测,直到我们可以看到 MRE / SSCCE,但这看起来很可疑“它被添加到框架中”。框架内容窗格的默认布局是
BorderLayout,它可以容纳CENTER中的一个组件。根据上面的代码sn-p,pane2和pane3都被添加到CENTER中(没有指定约束时默认。 -
..(未指定约束时的默认值)。我通常通过在框架中添加
JPanel来解决这些怪癖 - 明确设置布局,然后在该面板中添加其他所有内容。
标签: java swing jscrollpane jtextarea