Defaultlistmodel从jtextfield添加两次项



我正试图使一个应用程序发送由用户添加到我的SQL服务器的字符串的数量。然而,当我试图从jtextfield添加字符串到我的jlist时,它会被添加两次。

事情是这样的

user向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

当用户确定列表已经完成时,他点击"下一步"按钮,然后sendArraytoDB(JList list)方法被调用

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

等等……

我的运气不好,我的数据库显示有两个名字发送…我不能发布图片,所以就像

      aa      brand
       1
       2      "the string i sent"

在我的记录之前总是有一个空记录…为了看看发生了什么,我在发送它之前计算了列表的大小

int f = list.getModel().getSize();
        System.out.print(f);

,答案是2…如果我输入3条记录,它是6…等等…

我将问题缩小到模型,因为将addBrand()方法更改为

public void addBrand() {
            String all = "xghxc";       
            model.addElement(all);
}

无礼地显示两个"xghxc"同时被添加到我的列表中,在我自己惊讶的眼睛面前

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

我需要的是一个代码或建议或史密斯指向我不添加一个空的无用的记录在我的记录

这里是我的完整代码,谁有耐心和时间

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错误关于我的编码风格或我的技术,请张贴它

感谢您的宝贵时间

我将问题缩小到模型,因为将addBrand()方法更改为…

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

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

正如您在上面看到的,您向按钮添加了两次侦听器

最新更新