如何将JList对象添加到BorderLayout类型面板?

时间:2013-11-28 05:06:27

标签: java swing layout jpanel jlist

我在尝试将JList添加到面板的WEST端时遇到了麻烦。

我能够通过使用另一个面板并将其添加到原始面板,在NORTH上成功添加文本字段和搜索按钮。

JPanel panelShop = new JPanel();

    // Example of items in the scrollbar list
    String[] results = { "Result 1", "Result 2", "Result 3", "Result 4"};
    JList searchList = new JList(results);
    searchList.setLayoutOrientation(JList.VERTICAL);
    // Sets the number of items to display without requiring to scroll
    //searchList.setVisibleRowCount(4);
    panelShop.add(searchList, BorderLayout.WEST);

当我尝试将JList添加到原始面板的WEST边框时,问题是最后一行代码。

什么都没有出现。

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

public class TextJpanel extends JFrame {

public TextJpanel() {
    JPanel panelShop = new JPanel();
    panelShop.setLayout(new GridLayout());
    // Example of items in the scrollbar list
    String[] results = { "Result 1", "Result 2", "Result 3", "Result 4" };
    JList searchList = new JList(results);
    searchList.setLayoutOrientation(JList.VERTICAL);
    // Sets the number of items to display without requiring to scroll
    // searchList.setVisibleRowCount(4);
    panelShop.add(searchList, BorderLayout.WEST);
    add(panelShop);
}

public static void main(String[] args) {
    TextJpanel test = new TextJpanel();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.setSize(200, 200);
    test.setVisible(true);

}
}

确保您是否要将gridlayout用于JPanel,然后您必须将GridLayout管理器设置为此面板。