简体   繁体   English

遍历 List 但它只显示最后一项

[英]Iterating through List but it only shows last item

What I am trying to achieve is have one JLabel to display multiple items from a List .我想要实现的是有一个JLabel来显示List多个项目。

I have defined the list as below but when I test the code my method to iterate through the list, after a button click, only shows the last item in the list which is "DONE!"我已将列表定义如下,但是当我测试代码以遍历列表的方法时,单击按钮后,仅显示列表中的最后一项"DONE!" . .

I am trying to accomplish displaying only the next item in the list after each button click on one JLabel .我试图在每个按钮单击一个JLabel显示列表中的下一项

public class ScoutGUI extends javax.swing.JFrame {

    /**
     * Creates new form ScoutGUI
     */
    List<String> strings = Arrays.asList("Do you mind Clutter in Room?", "Do you mind alarm clocks?","Do you mind loud visitors?","Can you sleep with lights on?","Do you mind noise past Midnight?",
        "Do you consider yourself as an introvert?", "Do you consider yourself as an extrovert?","Do you like to go to parties?","Do you drink alcoholic beverages?(21+)", "DONE!");


    ArrayList<Student> obj = new ArrayList<>();
    String name , email , gender , major , year , language , building ;
    int id , i;
    public ScoutGUI() {
        initComponents();
    }

    public ScoutGUI(int a) {
        i = a;
        initComponents();

    }

    /**
     * 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() {

        panel1 = new java.awt.Panel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setFont(new java.awt.Font("Courier", 0, 13)); // NOI18N
        jButton1.setText("NO");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Courier", 0, 13)); // NOI18N
        jButton2.setText("YES");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 255, 153)));

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addComponent(jButton1)
                .addGap(94, 94, 94)
                .addComponent(jButton2)
                .addContainerGap(129, Short.MAX_VALUE))
            .addGroup(panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(68, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //skip and never

        buttonpressActionPerformed();

    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //match and update

        buttonpressActionPerformed();

    }                                        

    private void buttonpressActionPerformed() { 


       // int i = 0;


        Iterator<String> iterator = strings.iterator();


        //for (String strin : strings)  
        while (iterator.hasNext())

        {   

            //if (jButton2.isSelected() || jButton1.isSelected())
            //{
            jLabel1.setText(iterator.next());
            //}       

        }

    }
    /**
     * @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(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ScoutGUI.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 ScoutGUI().setVisible(true);
            }
        });
    }

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

Your current code always overrides the current text in the JPanel, and it does that so fast, that you don't see it.您当前的代码总是会覆盖 JPanel 中的当前文本,而且速度如此之快,以至于您看不到它。 Instead of using the Iterator, get the next item in the list by defining an int variable that gets incremented every press.不使用迭代器,而是通过定义一个每次按下都会递增的 int 变量来获取列表中的下一项。
The index variable is a public int in this example:在这个例子中, index变量是一个公共整数:

 jLabel1.setText(strings.get(index));
 if (index < strings.size()-1) 
        index++;

No loops, that's everything needed in your method.没有循环,这就是您的方法所需的一切。

In order to locate next string from collection, you need somehow know about current item.为了从集合中找到下一个字符串,您需要以某种方式了解当前项目。

One approach is to store index (or iterator) in a field:一种方法是在字段中存储索引(或迭代器):

List<String> strings=<...>
// 1. store index    
int sentenceIndex = 0; 
// 2. store iterator. You could get ConcurrentModificationException if change list and then use iterator.
Iterator<String> iterator = strings.getIterator();
private void buttonpressActionPerformed() { 
// 1. use index. 
if (sentenceIndex < strings.size()-1) { // avoid IndexOutOfBoundException
  String nextSentence = strings.get(sentenceIndex++);
}
// 2. use iterator
if (iterator.hasNext()) {
  String nextSentence = iterator.next();
}

But in fact you don't need to store something:但实际上你不需要存储一些东西:

// 3. calculate current index
String currentSentence = jLabel1.getText();
int currentIndex = strings.indexOf(currentSentence);
int nextIndex = incrementIndex(currentIndex);
String nextSentence = strings.get(nextIndex );

Note that I suggest new method incrementIndex .请注意,我建议使用新方法incrementIndex In it you could add not only lenght check but also jumping from last element to the first or just random selecting.在其中,您不仅可以添加长度检查,还可以从最后一个元素跳转到第一个元素或只是随机选择。

Each method has pro and contras:每种方法各有利弊:

  1. index require boundary checks索引需要边界检查

  2. iterator limits list updating迭代器限制列表更新

  3. index calcucaliton also require boundary checks and label1 should have correct initial value索引计算也需要边界检查并且label1应该有正确的初始值

    I would prefer storing index but it's your choice我更喜欢存储索引,但这是您的选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM