将字符串数组添加到 JList

Add a String Array to a JList

我试图将我的字符串数组放入 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);
}
        });

您的代码没问题,请尝试通过代码在其他地方查找错误。这是一个例子,证明你的这部分代码确实可行,这可能会帮助你发现错误。

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);
}
}