【问题标题】:Display each array list element in turn when a button is clicked单击按钮时依次显示每个数组列表元素
【发布时间】:2021-06-01 10:58:33
【问题描述】:

我使用 Java 制作了JFrame

我得到一个arraylist =[1,2,3,4],每当我单击下一个按钮时,列表中的下一个数字应该显示在JLabel 中。 我已经编写了代码,但问题是当我运行文件时它显示 "1" 并且当我单击下一个按钮时它在标签中显示 42 和 3 未显示。

我该如何解决这个问题?

public class prac extends javax.swing.JFrame {
    ArrayList<Integer>arr=new ArrayList<>();
        

    /**
     * Creates new form prac
     */
    
    public prac() {
        initComponents();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        String s=String.valueOf(arr.get(0));
        jLabel1.setText(s);
    }
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("next");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(124, 124, 124)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(77, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(81, 81, 81))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //System.out.println(lis);
        int i;
        
        for(i=1;i<arr.size();i++)
        {
            String d=String.valueOf(arr.get(i));
           jLabel1.setText(d);
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(prac.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(prac.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(prac.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(prac.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new prac().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

运行文件后

点击下一步后

【问题讨论】:

  • jButton1ActionPerformed 遍历整个列表并设置每次迭代的值,因此它总是只会在最后一个结束。
  • jLabel1.setText(d);在你的 for 循环中,所以每次迭代都会改变你的值。
  • @takendarkk 是的,这就是正在发生的事情......如何解决

标签: java swing arraylist


【解决方案1】:

如果您真的只想循环遍历数字 1 到 4,则根本不需要数组。您只需要读取标签的当前值并将其递增,如果递增为 5,则将其更改回 1。

private static void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Integer i = Integer.parseInt(jLabel1.getText());
    i++;
    if (i == 5) i = 1;
    jLabel1.setText(i.toString());
}

但是,如果您确实需要从数组中读取值,因为它可能不是连续的,您可以在数组中查找当前值并增加索引。

private static void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Integer i = Integer.parseInt(jLabel1.getText());
    int index = arr.indexOf(i);
    index++;
    if (index == 3) index = 0;
    jLabel1.setText(arr.get(index).toString());
}

注意:如果数组中有重复值,第二种方法将不起作用。

【讨论】:

    【解决方案2】:

    只跑过 1-4

    如 cmets 中所述,jButton1ActionPerformed 方法中的 for 循环不正确。你应该:

    • 取现有值

    • 加一

    • 如果超过限制,则重置为 1

       private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
           int limit = arr.size(); //or just 4?
           String d=jLabel.getText(); //take old one
           //if no value was set before..
           if (d.length()==0) d = "0";
           int num = Integer.parseInt(d) + 1; //takes next one
           if (num>limit) num = 1; //resets to 1 if needed
           jLabel1.setText(""+num);
       }  
      

    从 ArrayList 中取值

    ArrayList 获得类似的计划,但不仅仅是 +1,你:

    • 在列表中查找旧值的索引,
    • 索引加一,
    • 如果超出范围,则重置为 0,
    • 将 JLabel 的文本设置为新索引处 List 的值

    .

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        String d = jLabel1.getText(); //take from old one
        //if no value was set before, just sets to -1, so after +1 would be at idx 0
        if (d.length()==0) d = "-1";
        int parsedOldValue = Integer.parseInt(d); //gets int from String
        int newIndex = arr.indexOf(parsedOldValue) + 1; //takes next index
        if (newIndex >= arr.size()) newIndex = 0; //if exceeds, takes 0th
        jLabel1.setText(""+arr.get(newIndex));
    }  
    

    【讨论】:

    • 它不起作用。它只显示 arraylist 的第一个元素
    • @151_ANKITASAHA - 我编辑了倒数第二行 l.size() 更改为 arr.size()。我还测试了代码,如果应用正确,它必须工作。两个选项都在选项中循环。你能说出我的哪个选项对你来说失败了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多