【问题标题】:Add a String Array to a JList将字符串数组添加到 JList
【发布时间】:2018-12-29 14:38:45
【问题描述】:

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

【问题讨论】:

  • 如果您有问题,请向我们展示一个 MCVE:stackoverflow.com/help/mcve。因为不清楚您到底在尝试什么,以及您尝试过和未尝试过什么。
  • @Marcel。很好的建议。还有一个提示:评论中的[mcve] 会自动扩展为minimal reproducible example
  • Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
  • 当你按下这个btnTestList(我猜它是一个按钮)时,字符串数组被设置为JList。你按下这个按钮了吗?
  • 我当然按了

标签: java arrays swing jlist windowbuilder


【解决方案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);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-16
    • 2012-12-15
    • 2011-04-03
    • 2015-02-15
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多