2017-08-14 5 views
2

JLabelは、Listの複数のアイテムを表示するようにしています。リストを反復するが、最後のアイテムしか表示されない

私は以下のようにリストを定義したが、私はボタンのクリック後、リストを反復処理するコードに私のメソッドをテストするとき、唯一の"DONE!"あるリストに最後の項目を示しています。

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     
} 
+1

'jLabel1.setText(jLabel1.getText()+」「+ iterator.next());返信用' –

+0

おかげ。私は一度に一つずつ見せようとしていますが。提供したソリューションは、リスト内のすべてのアイテムをjLabel1に一度に表示します。ボタンをクリックした後に、どのように各ディスプレイを表示させるのですか?この場合、ボタンを押すとjButton1( "YES")とjButton2( "NO")になります。 – user5301179

答えて

1

現在のコードは、JPanelの現在のテキストを常に上書きしますが、それは表示されないほど速くなります。イテレータを使用する代わりに、毎回インクリメントされるint変数を定義して、リスト内の次の項目を取得します。
index変数は、この例では、公共のintです:

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

ないループ、それはあなたの方法で必要なものがすべてです。

+0

ありがとうございました。これは完璧に動作し、私がリストを反復するためにはるかに効率的な方法と思われます。 – user5301179

0

コレクションから次の文字列を検索するには、何らかの方法で現在のアイテムについて知っておく必要があります。

一つのアプローチは、フィールドにインデックス(またはイテレータ)を格納することです。

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

しかし、実際には、あなたが何かを保存する必要はありません。私は新しい方法を提案

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

注意incrementIndex。それには長さチェックだけでなく、最後の要素から最初の要素へのジャンプ、またはランダムな選択まで追加できます。

各メソッドは、プロ持ち、コントラ:

  1. インデックスが境界チェック私は
  2. インデックスcalcucalitonも境界チェックを必要としlabel1が正しい初期値を持つ必要があります

    を更新

  3. イテレータの制限のリストを要求インデックスを格納することをお勧めしますが、それはあなたの選択です

関連する問題