繁体   English   中英

如何使用字符串将项目添加到 Java 列表中?

[英]How can I add items into a java list using strings?

我正在尝试做一个学校项目,但我被卡住了。 基本上,我必须做一家药店,您必须在其中登录,然后您必须从 Java 列表中选择一个项目然后购买。

登录代码:

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.lang.Object;
import javax.swing.JOptionPane;

public class Login extends javax.swing.JFrame{
    public Login() {
        initComponents();

        //placeholder pt username
        final String placeholderUsername = "Username";
        jUsername.setText(placeholderUsername);    
        jUsername.addFocusListener(new FocusListener() {
    private boolean showingPlaceholder = true;
            public void focusGained(FocusEvent e) {
                    if (showingPlaceholder) {
                            showingPlaceholder = false;
                            jUsername.setText("");
                    }
            }
            public void focusLost(FocusEvent arg0) {
                    if (jUsername.getText().isEmpty()) {
                            jUsername.setText(placeholderUsername);
                            showingPlaceholder = true;
                    }
            }
        });

        //placeholder pt parola
        final String placeholderParola = "Parola";
        jParola.setText(placeholderParola);    
        jParola.addFocusListener(new FocusListener() {
    private boolean showingPlaceholder = true;
            public void focusGained(FocusEvent e) {
                    if (showingPlaceholder) {
                            showingPlaceholder = false;
                            jParola.setText("");
                    }
            }
            public void focusLost(FocusEvent arg0) {
                    if (jParola.getText().isEmpty()) {
                            jParola.setText(placeholderParola);
                            showingPlaceholder = true;
                    }
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jFereastraLogin = new javax.swing.JPanel();
        jUsername = new javax.swing.JTextField();
        jParola = new javax.swing.JPasswordField();
        jButonLogin = new javax.swing.JButton();
        jButonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jFereastraLogin.setBackground(new java.awt.Color(204, 204, 255));
        jFereastraLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));
        jFereastraLogin.setPreferredSize(new java.awt.Dimension(400, 400));
        jFereastraLogin.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jUsername.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jUsername.setPreferredSize(new java.awt.Dimension(10, 20));
        jUsername.setSelectedTextColor(new java.awt.Color(0, 0, 0));
        jUsername.setSelectionColor(new java.awt.Color(0, 0, 0));
        jFereastraLogin.add(jUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, 300, 25));

        jParola.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jParola.setSelectedTextColor(new java.awt.Color(0, 0, 0));
        jParola.setSelectionColor(new java.awt.Color(0, 0, 0));
        jFereastraLogin.add(jParola, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 100, 300, 25));

        jButonLogin.setText("Login");
        jButonLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButonLoginActionPerformed(evt);
            }
        });
        jFereastraLogin.add(jButonLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 140, 100, 20));

        jButonCancel.setText("Cancel");
        jButonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButonCancelActionPerformed(evt);
            }
        });
        jFereastraLogin.add(jButonCancel, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 140, 100, 20));

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

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

    private void jButonCancelActionPerformed(java.awt.event.ActionEvent evt) {                                             
        System.exit(0);
    }                                            

    private void jButonLoginActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String uname=jUsername.getText();
        String pword=jParola.getText();
        if(uname.equals("admin") && pword.equals("admin")){
            Home ho=new Home();
            ho.setVisible(true);
            this.dispose();
        }
        else{

            JOptionPane.showMessageDialog(rootPane, "Username sau parola incorecte");
        }
    }                                           

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButonCancel;
    private javax.swing.JButton jButonLogin;
    private javax.swing.JPanel jFereastraLogin;
    private javax.swing.JPasswordField jParola;
    private javax.swing.JTextField jUsername;
    // End of variables declaration                   
}

这个很好用。 登录后,您被重定向到主页:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Home extends javax.swing.JFrame {

    public Home() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jFereastraLogin = new javax.swing.JPanel();
        jPlafar = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListaPlante = new javax.swing.JList<>();
        jButtonCumpara = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jFereastraLogin.setBackground(new java.awt.Color(204, 204, 255));
        jFereastraLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
        jFereastraLogin.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPlafar.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        jPlafar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jPlafar.setText("PLAFAR");
        jFereastraLogin.add(jPlafar, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 10, 580, 30));

        jListaPlante.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jListaPlante.setModel(new javax.swing.AbstractListModel<String>(){
            String[] listaplante = new String[10];

            public void citeste(){
                System.out.println("daaaa");
                /*int c;
                int k=0;
                String planta = "";
                FileReader f = null;
                try {
                    f = new FileReader("Plante.txt");
                    while ((c = f.read()) != -1) {
                        planta = planta + (char)c; // formez numele plantei
                    }
                    listaplante[k] = planta;
                    k++;
                    planta = "";
                    f.close();
                }
                catch (FileNotFoundException e) {
                    System.out.println("Fisierul nu a fost gasit");
                }
                catch (IOException e) {
                    System.out.println("Eroare la citire");
                }
                */

                BufferedReader objReader = null;
                int k=0;
                try {
                    String strCurrentLine;
                    objReader = new BufferedReader(new FileReader("Plante.txt"));
                    while ((strCurrentLine = objReader.readLine()) != null) {
                        System.out.println(strCurrentLine);
                        listaplante[k] = strCurrentLine;
                        k++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (objReader != null)
                        objReader.close();
                    }catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }
            public int getSize() { return listaplante.length; }
            public String getElementAt(int i) { return listaplante[i]; }
        });
        jScrollPane1.setViewportView(jListaPlante);

        jFereastraLogin.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 560, 50));

        jButtonCumpara.setText("CUMPARA");
        jButtonCumpara.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCumparaActionPerformed(evt);
            }
        });
        jFereastraLogin.add(jButtonCumpara, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 160, -1, -1));

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

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

    private void jButtonCumparaActionPerformed(java.awt.event.ActionEvent evt) {                                               

    }                                              


    public static void main(String args[]) {
        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(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Home().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonCumpara;
    private javax.swing.JPanel jFereastraLogin;
    public javax.swing.JList<String> jListaPlante;
    private javax.swing.JLabel jPlafar;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
}

有人能解释一下为什么函数“citeste()”不起作用? 我试图从文件中读取药用植物,然后将它们放入一个字符串数组中。 问题是当我运行项目(GUI)时,这个字符串数组看起来没有链接到 jList。 该列表是空的。

有人可以帮助我吗?

目前您的方法 citeste 从未被调用。

我稍微调整了您的代码以使用 listaplante 数组启动 jlist。

您正在尝试在 jlist 的集合模型中添加值,这看起来不是很干净。

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class Home extends javax.swing.JFrame {

        public Home() {
            initComponents();
        }
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {

            jFereastraLogin = new javax.swing.JPanel();
            jPlafar = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();

            jButtonCumpara = new javax.swing.JButton();

            String[] listaplante = new String[10];
            BufferedReader objReader = null;
                    int k=0;
                    try {
                        String strCurrentLine;
                        objReader = new BufferedReader(new FileReader("Plante.txt"));
                        while ((strCurrentLine = objReader.readLine()) != null) {
                            System.out.println(strCurrentLine);
                            listaplante[k] = strCurrentLine;
                            k++;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (objReader != null)
                            objReader.close();
                        }catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }

                }

            jListaPlante = new javax.swing.JList<>(listaplante);
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jFereastraLogin.setBackground(new java.awt.Color(204, 204, 255));
            jFereastraLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
            jFereastraLogin.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

            jPlafar.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
            jPlafar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jPlafar.setText("PLAFAR");
            jFereastraLogin.add(jPlafar, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 10, 580, 30));

            jListaPlante.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jListaPlante.setModel(new javax.swing.AbstractListModel<String>(){
                public int getSize() { return listaplante.length; }
                public String getElementAt(int i) { return listaplante[i]; }
            });
            jScrollPane1.setViewportView(jListaPlante);

            jFereastraLogin.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 560, 50));

            jButtonCumpara.setText("CUMPARA");
            jButtonCumpara.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonCumparaActionPerformed(evt);
                }
            });
            jFereastraLogin.add(jButtonCumpara, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 160, -1, -1));

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

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

        private void jButtonCumparaActionPerformed(java.awt.event.ActionEvent evt) {                                               

        }                                              


        public static void main(String args[]) {
            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(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Home().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                     
        private javax.swing.JButton jButtonCumpara;
        private javax.swing.JPanel jFereastraLogin;
        public javax.swing.JList<String> jListaPlante;
        private javax.swing.JLabel jPlafar;
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                   
    }

您的方法citeste从未被调用,因此您的列表是空的您应该在构造函数中填充列表,或者检查您继承的方法getSizegetElementAt中的列表是否为空,并从那里调用您的citeste 确保你没有进入无限循环:) 你应该用@Override 注释你的 getSize 和 getElementAt。 您可以将内部类修改为如下所示:

jListaPlante.setModel(new javax.swing.AbstractListModel<String>(){
            String[] listaplante = new String[10];
            Boolean isInitialized = false;

            private void citeste(){
                System.out.println("daaaa");
                /*int c;
                int k=0;
                String planta = "";
                FileReader f = null;
                try {
                    f = new FileReader("Plante.txt");
                    while ((c = f.read()) != -1) {
                        planta = planta + (char)c; // formez numele plantei
                    }
                    listaplante[k] = planta;
                    k++;
                    planta = "";
                    f.close();
                }
                catch (FileNotFoundException e) {
                    System.out.println("Fisierul nu a fost gasit");
                }
                catch (IOException e) {
                    System.out.println("Eroare la citire");
                }
                */

                BufferedReader objReader = null;
                int k=0;
                try {
                    String strCurrentLine;
                    objReader = new BufferedReader(new FileReader("Plante.txt"));
                    while ((strCurrentLine = objReader.readLine()) != null) {
                        System.out.println(strCurrentLine);
                        listaplante[k] = strCurrentLine;
                        k++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (objReader != null)
                        objReader.close();
                    }catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }
            public int getSize() {
                if (!isInitialized) {
                    citeste();
                    isInitialized = true;
                }
                return listaplante.length; 
            }
            public String getElementAt(int i) { 
                if (!isInitialized) {
                    citeste();
                    isInitialized = true;
                }
                return listaplante[i]; 
            }
        });

暂无
暂无

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

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