Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Defaultlistmodel从jtextfield中添加两次项_Java_Jtextfield_Jlist_Defaultlistmodel - Fatal编程技术网

Java Defaultlistmodel从jtextfield中添加两次项

Java Defaultlistmodel从jtextfield中添加两次项,java,jtextfield,jlist,defaultlistmodel,Java,Jtextfield,Jlist,Defaultlistmodel,我试图创建一个应用程序,将用户添加的大量字符串发送到我的SQL server。但是,当我尝试从jtextfield向jlist添加字符串时,它会被添加两次 事情是这样的 用户向jtextfield添加一个名称。当他点击+按钮时,它被发送到jlist public void addBrand() { int index = BrandList.getSelectedIndex(); // get selected index if (index == -1) { // no se

我试图创建一个应用程序,将用户添加的大量字符串发送到我的SQL server。但是,当我尝试从jtextfield向jlist添加字符串时,它会被添加两次

事情是这样的

用户向jtextfield添加一个名称。当他点击+按钮时,它被发送到jlist

public void addBrand() {

    int index = BrandList.getSelectedIndex(); // get selected index
    if (index == -1) { // no selection, so insert at beginning
        index = 0;
    } 
                else { // add after the selected item
        index++;
    }

    model.insertElementAt(BrandLbl.getText(), index);

    BrandLbl.setText(null);


}
在这里一切正常我看到一个项目添加到我的jlist中

当用户确定列表已完成时,他点击下一步按钮并 调用sendArraytoDBJList列表方法

public static void sendArraytoDB(JList<String> list){
        Connection con = null;
        PreparedStatement stm = null;
        String updQuery = "insert into brand_names (name) values (?)";

        try{
        con = DB.getConnection();
        //con.setAutoCommit(false);
        int x =1;
       stm = con.prepareStatement(updQuery);


        int f = list.getModel().getSize();
        System.out.print(f);
        for (int i=0; i<list.getModel().getSize(); i++){

            String name =list.getModel().getElementAt(i);
            stm.setString(x, name);
            //try{
            stm.executeUpdate();
            //}finally{
            //stm.close();
            //}
        }  
           }catch(SQLException ex){
            System.out.printf("error while sending array to db");
            ex.printStackTrace();
        }finally{
            if (stm != null){
在我的记录之前,列表中还有一条空记录。。。 试图看到wtf正在发生,我在发送前计算了列表大小

int f = list.getModel().getSize();
        System.out.print(f);
答案是2。。。如果我输入3条记录,则为6。。等等

由于将addBrand方法更改为

public void addBrand() {
            String all = "xghxc";       
            model.addElement(all);
}
在我惊讶的眼前,无礼地显示两个xghxc同时被添加到我的列表中

我搜索了谷歌,但它甚至没有与我类似的问题:

我需要的是一个代码或建议或smth,以指示我不要在我的记录中添加空的无用记录

这是我的全部代码,供有耐心和时间的人使用

MyMain.java

    package tweGraf;

import javax.swing.JFrame;


public class MyMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Gui g = new Gui();
                DB.MakePool();


        g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        g.setSize(1000, 800);
        g.setVisible(true);


    }

}
Gui.java

    package tweGraf;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Gui extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

        private JFrame frameYesNo = new JFrame();

        String message = "all data will perish. are you sure";

    private JPanel Container = new JPanel(); // panels
    private JPanel FirstPanel = new JPanel();
    private JPanel NewSession = new JPanel();
    private JPanel LoadSession = new JPanel();
    private JPanel LoadList = new JPanel();


    private JPanel GraphSub1 = new JPanel();
    private JPanel GraphSub2 = new JPanel();
    private JPanel GraphSub3 = new JPanel();

    private JTabbedPane GraphPanel = new JTabbedPane();

    private JButton NewSessBtn = new JButton(); // buttons
    private JButton LoadSessBtn = new JButton();
    private JButton BackFP = new JButton();
    private JButton plusBrand = new JButton();
    private JButton minusBrand = new JButton();
    private JButton Next = new JButton();

    private JLabel EnterBrandLbl = new JLabel(
            "Please insert brands for analysis "); // Labels

    private JTextField BrandLbl = new JTextField(20); // textfields

    public  DefaultListModel<String> model = new DefaultListModel<String>      
    public JList BrandList = new JList(model); // list
    private JScrollPane MyScrollPane = new JScrollPane(BrandList);

    private CardLayout cardLayout = new CardLayout(); // layouts

    private GridBagLayout MyLayout = new GridBagLayout();
    GridBagConstraints MyConstr = new GridBagConstraints();

    public Gui() {

        super("twegraph");

        NewSessBtn.setText("New Session"); // button configuration
        LoadSessBtn.setText("Load Session");
        BackFP.setText("Back");
        plusBrand.setText("+");
        minusBrand.setText("-");
        Next.setText("Next");

        actionListener al = new actionListener();

        NewSessBtn.addActionListener(al); // add action listeners
        LoadSessBtn.addActionListener(al);
        BackFP.addActionListener(al);
        plusBrand.addActionListener(al);
        minusBrand.addActionListener(al);
        Next.addActionListener(al);
        plusBrand.addActionListener(al);
        minusBrand.addActionListener(al);

        Container.setLayout(cardLayout); // panels to container+

        Container.add(FirstPanel, "FirstPanel");
        Container.add(NewSession, "NewSession");
        Container.add(LoadSession, "LoadSession");
        Container.add(GraphPanel, "GraphPanel");
        Container.add(LoadList, "LoadList");

        FirstPanel.setLayout(MyLayout); // first panel
        MyConstr.gridwidth = 3;
        MyConstr.gridheight = 3;
        MyConstr.weightx = 1.0;
        MyConstr.weighty = 1.0;
        MyConstr.ipadx = 100;
        MyConstr.ipady = 50;
        MyConstr.insets = new Insets(50, 20, 50, 20);

        MyConstr.gridx = 1;
        MyConstr.gridy = 0;
        MyConstr.anchor = GridBagConstraints.NORTH;
        MyLayout.setConstraints(NewSessBtn, MyConstr);
        FirstPanel.add(NewSessBtn);

        MyConstr.gridx = 1;
        MyConstr.gridy = 2;
        MyConstr.anchor = GridBagConstraints.SOUTH;
        MyLayout.setConstraints(LoadSessBtn, MyConstr);
        FirstPanel.add(LoadSessBtn);

        NewSession.setLayout(MyLayout); // New Session panel

        MyConstr.gridwidth = 3;
        MyConstr.gridheight = 3;
        MyConstr.ipadx = 0; // size
        MyConstr.ipady = 0; // size
        MyConstr.gridx = 0;
        MyConstr.gridy = 2;
        MyConstr.insets = new Insets(10, 20, 10, 20);

        MyConstr.anchor = GridBagConstraints.SOUTHWEST;
        MyLayout.setConstraints(BackFP, MyConstr);
        NewSession.add(BackFP);

        MyConstr.anchor = GridBagConstraints.SOUTHEAST;
        MyLayout.setConstraints(Next, MyConstr);
        NewSession.add(Next);

        MyConstr.ipadx = 0; // size
        MyConstr.ipady = 0; // size
        MyConstr.gridx = 0; // place
        MyConstr.gridy = 1; // place
        MyConstr.insets = new Insets(0, 0, 0, 0);

        MyConstr.anchor = GridBagConstraints.PAGE_START;
        MyLayout.setConstraints(EnterBrandLbl, MyConstr);
        NewSession.add(EnterBrandLbl);

        MyConstr.gridx = 0;
        MyConstr.gridy = 1;
        MyConstr.anchor = GridBagConstraints.CENTER;
        MyLayout.setConstraints(BrandLbl, MyConstr);
        NewSession.add(BrandLbl);

        MyConstr.gridx = 2;
        MyConstr.gridy = 1;
        MyConstr.anchor = GridBagConstraints.LAST_LINE_START;
        MyLayout.setConstraints(plusBrand, MyConstr);
        NewSession.add(plusBrand);

        MyConstr.gridx = 2;
        MyConstr.gridy = 1;
        MyConstr.anchor = GridBagConstraints.LAST_LINE_END;
        MyLayout.setConstraints(minusBrand, MyConstr);
        NewSession.add(minusBrand);

        MyConstr.ipadx = 0; // size
        MyConstr.ipady = 0;
        MyConstr.gridx = 0;
        MyConstr.gridy = 1;
        MyConstr.anchor = GridBagConstraints.SOUTH;
        MyLayout.setConstraints(MyScrollPane, MyConstr);
        NewSession.add(MyScrollPane);


        GraphPanel.addTab("overall",GraphSub1);             //Graph panel
        GraphPanel.addTab("tweets/time",GraphSub2);
        GraphPanel.addTab("fame",GraphSub3);



        this.setContentPane(Container);

        cardLayout.show(Container, "FirstPanel");

    }

    public class actionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {

            JButton src = (JButton) event.getSource();
                        int answer = 0;

                        if (src.equals(NewSessBtn))
                        {
                                answer =       JOptionPane.showConfirmDialog(frameYesNo, message);
                                if (answer == JOptionPane.YES_OPTION) {
                                    cardLayout.show(Container,        "NewSession");
                                    try {
                                        DB.flushData();
                                        } catch (SQLException ex) {
                                        Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                } else if (answer == JOptionPane.NO_OPTION) {
                                    frameYesNo.dispose();
                                }
                        }   
            if (src.equals(LoadSessBtn)){
                cardLayout.show(Container, "LoadSession");
                        }
            if (src.equals(BackFP)){
                cardLayout.show(Container, "FirstPanel");
                        }
            if (src.equals(Next)){

                cardLayout.show(Container, "GraphPanel");
                                DB.sendArraytoDB(BrandList);

            }

            if (src.equals(plusBrand)){

                addBrand();
                        }           
            if (src.equals(minusBrand))
                        {

                removeBrand();
                        }

        }
    }

    public void addBrand() {

        /*int index = BrandList.getSelectedIndex(); // get selected index
        if (index == -1) { // no selection, so insert at beginning
            index = 0;
        } 
                    else { // add after the selected item
            index++;
        }*/
                String all = "xghxc";
        //model.insertElementAt(BrandLbl.getText(), index);
                model.addElement(all);
        //BrandLbl.setText(null);


    }


    public void removeBrand() {
        int index2 = BrandList.getSelectedIndex();
                if (index2 != -1){
        model.remove(index2);
                }



        int size = model.getSize();

        if (size == 0) {
            minusBrand.setEnabled(false);

        } else {
            //if (index == model.getSize()) {
                //index--;
            //}

        }

    }



}
DB.java

    package tweGraf;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JList;

/**
 *
 * @author cheval
 */
public class DB {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/twegrahpdb";



   static final String USER = "root";
   static final String PASS = "Xrt38H0a";

    private static ComboPooledDataSource cdps = new ComboPooledDataSource();
    public static void MakePool(){
        try {
        cdps = new ComboPooledDataSource();
        cdps.setDriverClass(JDBC_DRIVER);
        cdps.setJdbcUrl(DB_URL);
        cdps.setUser(USER);
        cdps.setPassword(PASS);
        cdps.setMaxPoolSize( 50 );
        cdps.setMaxStatements(50);
        }catch(Exception ex){
            System.out.printf("error smth wrong happened");
        }
    }

        public static Connection getConnection() throws SQLException{
            return cdps.getConnection();
        }

        public static void flushData() throws SQLException{
            Statement stm = null;
            Connection con = null;
            try{
            con = DB.getConnection();
            stm = con.createStatement();
            String flushquery1 = "TRUNCATE json_cache";
            String flushquery2 = "TRUNCATE tweets";
            String flushquery3 = "TRUNCATE tweet_mentions";
            String flushquery4 = "TRUNCATE tweet_tags";
            String flushquery5 = "TRUNCATE tweet_urls";
            String flushquery6 = "TRUNCATE users";
            String flushquery7 = "TRUNCATE brand_names";
            stm.executeUpdate(flushquery1);
            stm.executeUpdate(flushquery2);
            stm.executeUpdate(flushquery3);
            stm.executeUpdate(flushquery4);
            stm.executeUpdate(flushquery5);
            stm.executeUpdate(flushquery6);
            stm.executeUpdate(flushquery7);
            }catch (SQLException e) {
                System.out.printf("error executing db clear");
            } finally {
                if (stm != null){
                    try{
                    stm.close();
                    System.out.printf("statement closed successfuly \n");
                    } catch (SQLException e){
                        System.out.printf("error closing statement");
                    }
                }
                if (con != null){
                    try{
                       con.close();
                       System.out.printf("connection closed succesfully \n");
                    } catch (SQLException e){
                        System.out.printf("error closing connection");

                    }
                }
            }

        }

        public static void sendArraytoDB(JList<String> list){
            Connection con = null;
            PreparedStatement stm = null;
            String updQuery = "insert into brand_names (name) values (?)";

            try{
            con = DB.getConnection();
            //con.setAutoCommit(false);
            int x =1;
           stm = con.prepareStatement(updQuery);


            int f = list.getModel().getSize();
            System.out.print(f);
            for (int i=0; i<list.getModel().getSize(); i++){

                String name =list.getModel().getElementAt(i);
                stm.setString(x, name);
                //try{
                stm.executeUpdate();
                //}finally{
                //stm.close();
                //}
            }  
               }catch(SQLException ex){
                System.out.printf("error while sending array to db");
                ex.printStackTrace();
            }finally{
                if (stm != null){

                    try {
                        stm.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
                if (con != null){
                    try {
                        con.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
    }
如果你仍然不知道,不关心我的实际问题,但仍然看到smth错误关于我的编码风格或我的技术plz张贴它

谢谢你的时间

自从将addBrand方法更改为

这告诉我addBrand方法被多次调用

    plusBrand.addActionListener(al);
    minusBrand.addActionListener(al);
    Next.addActionListener(al);
    plusBrand.addActionListener(al);
    minusBrand.addActionListener(al);

如上所示,您将侦听器添加到按钮上两次。

请参见smth关于我的编码风格的错误-变量名称不应以大写字符开头。请注意论坛如何像类名一样突出显示它们。类名也应该以大写字符.thnks开头作为通知
    plusBrand.addActionListener(al);
    minusBrand.addActionListener(al);
    Next.addActionListener(al);
    plusBrand.addActionListener(al);
    minusBrand.addActionListener(al);