Java Netbeans 8.0 Jframe GUI程序 - arraylist中的每个索引值都没有显示在jtextArea中的各行上

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Netbeans 8.0 Jframe GUI程序 - arraylist中的每个索引值都没有显示在jtextArea中的各行上相关的知识,希望对你有一定的参考价值。

我正在研究我课程中的另一个程序,我们应该创建一个程序,用一个整数的arraylist(即一个类的标记)执行多个函数。我的问题是,当我尝试按升序输出“marks”arraylist的值时,每个值都在它自己的行上,它只显示最近输入的值。

例如,如果我输入25然后输入54并单击“排序”按钮,则Jtextarea中仅显示54。我的代码如下所示,请注意问题在sortButtonActionPerformed方法中。

import java.util.*;
public class MarksGUI extends javax.swing.JFrame {

    ArrayList <Integer> marks = new ArrayList();
    ArrayList <Integer> marksSorted = new ArrayList();

    int numlvlR=0;
    int numlvl1=0;
    int numlvl2=0;
    int numlvl3=0;
    int numlvl4=0;


    public MarksGUI() {

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

        titleLabel = new javax.swing.JLabel();
        markLabel = new javax.swing.JLabel();
        markInput = new javax.swing.JTextField();
        addButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        analyzeField = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        classmarksField = new javax.swing.JTextArea();
        sortButton = new javax.swing.JButton();
        analyzeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        titleLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        titleLabel.setForeground(new java.awt.Color(0, 0, 204));
        titleLabel.setText("Marks Program");

        markLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        markLabel.setText("Student Mark:");

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        analyzeField.setEditable(false);
        analyzeField.setColumns(20);
        analyzeField.setRows(5);
        jScrollPane1.setViewportView(analyzeField);

        classmarksField.setEditable(false);
        classmarksField.setColumns(20);
        classmarksField.setRows(5);
        jScrollPane2.setViewportView(classmarksField);

        sortButton.setText("Sort");
        sortButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sortButtonActionPerformed(evt);
            }
        });

        analyzeButton.setText("Analyze");
        analyzeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                analyzeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 32, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(titleLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addComponent(markLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(markInput, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(86, 86, 86)
                .addComponent(sortButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(analyzeButton)
                .addGap(90, 90, 90))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(markInput, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(markLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(addButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sortButton)
                    .addComponent(analyzeButton))
                .addContainerGap(19, Short.MAX_VALUE))
        );

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

    //add method is working/////////////
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        int newMarks;

        newMarks = Integer.parseInt(markInput.getText());

        marks.add(newMarks);
        System.out.println(marks);//testing purposes




    }                                         
    //problem is in sort method//////////////
    private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           

        int biggestMark = largestMark();//YOU WERE HERE///////////////////////////////////////////////////////////////////////////////////////////
        for(int k = 0;k<marks.size();k++)
        {

            marksSorted.add((marks.get(k)));
            System.out.println(marksSorted);//testing purposes

        }
        for(int x = 0;x<marks.size();x++)
        {
            Collections.sort(marksSorted);
            classmarksField.setText(marksSorted.get(x)+"\n");
            System.out.println(marksSorted);//testing purposes
        }

    }**                                          
    //working//////////////////////
    private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        int maxMark, minMark, mark;
        analyzeField.setText("Class Average:"+classAverage()+"\n"+"Maximum Mark:"+largestMark()+"\n"+"Mininmum Mark:"+smallestMark()+"\n"+"Range of Marks:"+rangeofMarks()+"\n"+"Num at level 4:"+numlvl4+"\n"+"Num at level 3"+numlvl3+"\n"+"Num at level 2:"+numlvl2+"\n"+"Num at level 1:"+numlvl1+"\n"+"Num at level R:"+numlvlR);









    }                                             
    public int classAverage(){
        int marksTotal, marksAverage;
        marksTotal = 0;

        for(int i = 0; i<marks.size();i++){
            marksTotal = marksTotal+marks.get(i);
        }
        marksAverage = marksTotal/marks.size();
        return(marksAverage);   
    }
    public int smallestMark(){
        int smallestmarkValue;
        smallestmarkValue = 100;
        for(int y = 0; y<marks.size();y++){
            if(marks.get(y)<=smallestmarkValue)
            {
                smallestmarkValue = marks.get(y);
            }
            else
            {   
            }
        }
        return(smallestmarkValue);
    }
    public int largestMark(){
        int largestmarkValue;
        largestmarkValue = 0;
        for(int z = 0; z<marks.size();z++){
            if(marks.get(z)>=largestmarkValue)
            { 
                largestmarkValue = marks.get(z);
            }
            else
            {
            }

        }
        return(largestmarkValue);     
    }
    public int rangeofMarks(){
        int range;
        range = largestMark()-smallestMark();
        return(range);
    }
    public int numwitheachlevel(){
        int mark;
        mark = 0;

        for(int j = 0; j<marks.size();j++){
            mark = marks.get(j);
            if(mark<50)
            {
                numlvlR++;
            }
            else if((mark >= 50) && (mark < 60))
            {
                numlvl1++;
            }
            else if((mark >= 60) && (mark < 70))
            {
                numlvl2++;
            }
            else if((mark >= 70) && (mark < 80))
            {
                numlvl3++;
            }
            else if(mark >= 80)
            {
                numlvl4++;
            }

        //numeachlvl.addAll(numlvlR,numlvl1,numlvl2,numlvl3,numlvl4);
        //return(numeachlvl);//you were here///////////////////////////////////////////////////////////////////////////////

    }
    //System.out.println("Range:"+rangeofMarks());
    System.out.println("Largest mark"+largestMark()); 
    System.out.println("Smallest mark:"+smallestMark());
    System.out.println("Number at level R:"+numlvlR);
    System.out.println("Number at level 1:"+numlvl1);
    System.out.println("Number at level 2:"+numlvl2);
    System.out.println("Number at level 3:"+numlvl3);
    System.out.println("Number at level 4:"+numlvl4);

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


    // Variables declaration - do not modify                     
    private javax.swing.JButton addButton;
    private javax.swing.JButton analyzeButton;
    private javax.swing.JTextArea analyzeField;
    private javax.swing.JTextArea classmarksField;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField markInput;
    private javax.swing.JLabel markLabel;
    private javax.swing.JButton sortButton;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration                   
}
答案

。例如,如果我输入25然后输入54并单击“排序”按钮,则Jtextarea中仅显示54

for(int x = 0;x<marks.size();x++)
{
    Collections.sort(marksSorted);
    classmarksField.setText(marksSorted.get(x)+"\n");
    System.out.println(marksSorted);//testing purposes
}

如果从marks.size列表中获取数据,为什么使用markssorted来控制循环?排序不会创建数据的副本。

为什么每次循环都会对List进行排序?你期望改变什么?

你为什么要使用setText(...)?这将替换文本区域中的所有文本,因此您只能获取列表中的最后一个值。

使用JTextArea的append(...)方法。

以上是关于Java Netbeans 8.0 Jframe GUI程序 - arraylist中的每个索引值都没有显示在jtextArea中的各行上的主要内容,如果未能解决你的问题,请参考以下文章

如何让 JFrame 按钮在 Netbeans 中打开另一个 JFrame 类?

netbeans6.9.1中,如何能设置一个图片作为JFrame窗体的背景?

我如何将jframe对齐到netbeans中的窗口中心[关闭]

我可以在运行时在 netbeans 的 jframe 中添加一个组件吗?

使用netbeans7.0 建立JFrame窗体 后如何设置背景?

NetBeans IDE 7.4怎样创建桌面应用程序