i am trying to make an application that sends a number of string added by the user to my SQL server. however when i try to add an string to my jlist from jtextfield it gets added twice..
here is the thing
user adds a name to jtextfield . when he hits the + button it is send to 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);
}
all fine here i see one item added to my jlist
when the user decides the list is complete he hits the "next" button and the sendArraytoDB(JList list) method is called
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){
etc etc....
for my bad luck the my databse shows that there are two names sent.. i cant post images so its like
aa brand
1
2 "the string i sent"
the list has allways one more empty record before my record... trying to see wtf is happening i counted the list size just before i send it
int f = list.getModel().getSize();
System.out.print(f);
and the answer is 2 ... if i enter 3 records its 6 .. etc...
i narrowed the problem to the model since changing the addBrand() method to
public void addBrand() {
String all = "xghxc";
model.addElement(all);
}
impudently shows two of "xghxc" being added to my list at the same time in front of my very own amazed eyes
i searched google but it doesnt even have a similar problem to mine :(
what i need is a code or an advice or smth to point me to not adding an empty useless record amongst my records
here is my full code for anyone who has the patience and time
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);
}
}
}
}
}
if you still dont know dont care about my actual problem but STILL see smth wrong regarding my coding style or my techniques plz post it
thanks for your time
i narrowed the problem to the model since changing the addBrand() method to...
So this tells me the addBrand() method is called multiple times.
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Next.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
As you can see above you add the listener twice to the button.