将字符串数组添加到JList

时间:2018-12-29 14:38:45

标签: java arrays swing jlist windowbuilder

我正在尝试将字符串数组放入JList中,但是什么也没有发生。 我在做什么错了?

JList<String> list = new JList<String>();
list.setBounds(22, 111, 190, 395);
jpPanel.add(list);

btnTestList.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String [] testArray = {"a","b","c"};
                list.setListData( testArray);
}
        });

1 个答案:

答案 0 :(得分:1)

您的代码还可以,请尝试通过代码查找其他地方的错误。这是一个示例,演示您的代码的这一部分确实可行,可能会帮助您发现错误。

public class NewJPanel extends JFrame {
public NewJPanel() {
    this.setSize(400, 300);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container container = this.getContentPane();
    JPanel jpPanel = new JPanel ();
    container.add(jpPanel);

    GridBagLayout gridBagLayout = new GridBagLayout();
    jpPanel.setLayout(gridBagLayout);

    JButton btnTestList = new JButton("New button");
    jpPanel.add(btnTestList);

    JList<String> list = new JList<String>();
    GridBagConstraints gbc_list = new GridBagConstraints();
    gbc_list.fill = GridBagConstraints.BOTH;
    gbc_list.gridx = 0;
    gbc_list.gridy = 1;
    jpPanel.add(list, gbc_list);

    btnTestList.addActionListener(new ActionListener () {
        public void actionPerformed(ActionEvent e) {
             String [] testArray = {"a","b","c"};
             list.setListData( testArray);
        }
    });   
}


public static void main(String[] args) {
    NewJPanel jPnl = new NewJPanel ();
    jPnl.setVisible(true);
}
}