how to set values from sql database to java textbox? - java

When I try to access data from SQL Server, the data column is of type varchar. But I try to set it into textbox, I got these type of exception
Conversion failed when converting the varchar value '09ran01' to data type int
package src.ui;
import src.ui.ImageHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class AddAccount extends JPanel implements ActionListener, DocumentListener, KeyListener {
String imagefolder = ImageHandler.returnimagepath();
Image bgImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/src/ui/images/bgc.jpg"));
private static final long serialVersionUID = 1L;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
String iden[] = {"Student","Others"};
String type[] = {"Account User", "Walkthrough User"};
JLabel userid = new JLabel("USER ID");
JLabel name = new JLabel("FULL NAME");
JLabel pswrd = new JLabel("PASSWORD");
JLabel ident = new JLabel("IDENTIFICATION");
JLabel idno = new JLabel("ID NUMBER");
JLabel Add = new JLabel("ADDRESS");
JLabel acctype = new JLabel("ACCOUNT TYPE");
JTextField userFld = new JTextField(10);
JTextField nameFld = new JTextField(10);
JPasswordField pswrdFld = new JPasswordField(10);
JComboBox identC = new JComboBox(iden);
JComboBox actype = new JComboBox(type);
JTextField idFld = new JTextField(10);
JTextArea addArea = new JTextArea(10, 10);
JButton okButton = new JButton("OK");
JButton exitButton = new JButton("RESET");
JButton b1 = new JButton("SEARCH");
JScrollPane scroll = new JScrollPane(addArea);
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/cybman", "root", "");
} catch (Exception e) {
//System.out.println(e);
}
return conn;
}
public static Connection getConnection1() {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost\\BCA1:1433;databaseName=Old_Bhandarkars;user=sa;password=1234");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"SERVER ERROR");
//System.out.println(e);
}
return con;
}
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
public void paintComponent(Graphics g) {
g.drawImage(bgImage, 0, 0, this);
}
public void init() {
setLayout(null);
okButton.addActionListener(this);
b1.addActionListener(this);
exitButton.addActionListener(this);
pswrdFld.addActionListener(this);
pswrdFld.setEchoChar('*');
addArea.getDocument().addDocumentListener(this);
identC.addActionListener(this);
actype.addActionListener(this);
userid.setBounds(270, 20, 120, 20);
userFld.setBounds(470, 20, 140, 20);
b1.setBounds(670, 20, 100, 20);
name.setBounds(270, 70, 120, 20);
nameFld.setBounds(470, 70, 140, 20);
pswrd.setBounds(270, 120, 120, 20);
pswrdFld.setBounds(470, 120, 140, 20);
ident.setBounds(270, 170, 120, 20);
identC.setBounds(470, 170, 140, 20);
idno.setBounds(270, 220, 120, 20);
idFld.setBounds(470, 220, 140, 20);
acctype.setBounds(270, 270, 120, 20);
actype.setBounds(470, 270, 140, 20);
Add.setBounds(270, 320, 320, 20);
scroll.setBounds(470, 320, 140, 60);
okButton.setBounds(270, 410, 100, 20);
okButton.addKeyListener(this);
exitButton.setBounds(510, 410, 100, 20);
}
public AddAccount() {
init();
add(userid);
add(userFld);
add(name);
add(nameFld);
add(pswrd);
add(pswrdFld);
add(ident);
add(identC);
add(idno);
add(idFld);
add(acctype);
add(actype);
add(Add);
add(b1);
add(scroll);
add(okButton);
add(exitButton);
}
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public class Function
{
Connection con=getConnection1();
ResultSet rs;
public ResultSet find(String s)
{
int a=Integer.parseInt(s);
try{
Statement sta = con.createStatement();
String s1 = "select * from Members where Fld_Member_Id="+a+"";
rs = sta.executeQuery(s1);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"No connection");
//JOptionPane.showMessageDialog(null,ex.getMessage());
}
//JOptionPane.showMessageDialog(null,rs);
return rs;
}
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
char[] pass;
String uid;
String nam;
String add;
String id;
String idnum;
String actyp;
int amt = 0;
String datE;
if (str.equals("SEARCH")) {
Function f=new Function();
ResultSet rs=null;
String n1="Fld_First_Name";
String i1="Fld_Member_Id";
String address="Fld_PAddr";
uid = userFld.getText();
if(uid.equals(""))
{
JFrame msg=new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
}
// simple.main();
else
{
//idFld.setText(userFld.getText());
rs=f.find(userFld.getText());
// System.out.println("Fld_First_Name");
try{
if(rs.next()){
// int i = Integer.parseInt(rs.getString("Fld_First_Name"));
// int j = Integer.parseInt(rs.getString("Fld_Member_Id"));
// int k = Integer.parseInt(rs.getString("Fld_PAddr"));
nameFld.setText(rs.getString("Fld_First_Name"));
idFld.setText(rs.getString("Fld_Member_Id"));
addArea.setText(rs.getString("Fld_PAddr"));
}
else
{
JOptionPane.showMessageDialog(null,"No data");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
if (str.equals("OK")) {
try {
uid = userFld.getText();
nam = nameFld.getText();
pass = pswrdFld.getPassword();
add = addArea.getText();
idnum = idFld.getText();
id = (String) identC.getSelectedItem();
actyp = (String) actype.getSelectedItem();
datE = getDateTime();
String pwrd = new String(pass);
Connection conn = getConnection();
/*ERROR CHECKING*/
boolean success = true;
if (uid.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (nam.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the name", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (pwrd.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the password", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if ((!id.equals("Student")) && (idnum.equals(""))) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the identification number", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (add.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the address", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
}
/*end of ERROR CHECKING*/
if (success == true) {
///////////ENSURE/////////
JFrame msg = new JFrame();
int choice;
choice = JOptionPane.showConfirmDialog(msg, "Are you sure?", "Select your choice", JOptionPane.OK_CANCEL_OPTION);
/////////////////////////
if (choice == JOptionPane.OK_OPTION) {
str = "insert into account(userid,name,password,address,identification,identificationnum,amount,dates,acctype" + ") values (?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(str);
ps.setString(1, uid);
ps.setString(2, nam);
ps.setString(3, pwrd);
ps.setString(4, add);
ps.setString(5, id);
ps.setString(6, idnum);
ps.setInt(7, amt);
ps.setString(8, datE);
ps.setString(9, actyp);
int count;
count = ps.executeUpdate();
count++;
count--;
//////////////////////////////
ReportPanel.userC.addItem(uid);
ViewAccount.userC.addItem(uid);
if (actyp.equals("Account User")) {
RechargePanel.userC.addItem(uid);
}
//////////////////////////////
JFrame msg1 = new JFrame();
JOptionPane.showMessageDialog(msg1, "An account has been successfully created", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (choice == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(msg, "Account Creation Aborted", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
//conn.close();
} catch (SQLException e1) {
String error;
JFrame msg = new JFrame();
//error=e1.toString();
error = "Your entry for user id already exists";
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
String error;
JFrame msg = new JFrame();
error = e1.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
///////////////////////////////////////////////////////////////////////////
if (str.equals("RESET")) {
try {
userFld.setText("");
nameFld.setText("");
pswrdFld.setText("");
addArea.setText("");
idFld.setText("");
} catch (Exception e2) {
String error;
JFrame msg = new JFrame();
error = e2.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
///////////////////////////////////////////////////////////
public void keyPressed(KeyEvent key) {
//
}
/////////////////////////////////////////////////////
public void keyReleased(KeyEvent key) {
if (key.getSource() == pswrdFld) {
if (key.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
}
/////////////////////////////////////////////////
public void keyTyped(KeyEvent key) {
//
}
//////////////////////////////////////////////
}
How to set all values to textbox?
field name data type
---------------------------------------------------------------------
Fld_First_Name varchar
Fld_Member_Id varchar
Fld_PAddr nvarchar
SELECT * FROM Members where Fld_Member_Id='14932';
_____________________________________________________________________________
Fld_Member_Id Fld_First_Name Fld_PAddr
______________________________________________________________________________
14932 abc abc

In WHERE clause of a SQL query a varchar variables should be within a single quotes. Try String s1 = "select * from Members where Fld_Member_Id='"+a+"'";
add Single quotes into the statement.And i think it should work setText method that you mentioned if you pass a varchar value correctly.

If you are not sure what is the type of memberID, then use
idFld.setText(String.valueOf("Your value"));

Related

Error in Java project. Information is not displayed

Tell me, please, what could be the error, in the form on "View the list of products" it does not display a value, although it should display an array of parameters with products. The error in the IDE when creating the button is this: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot call "java.util.ArrayList.iterator()" because "stocks" is null. But in the file for the first information, but not displayed Help is needed!!!!
Stock class file code for storing product parameters
package com.company;
import java.io.Serializable;
class Stock implements Serializable {
private int warehouseNumber;
private String productName;
private double price;
private int count;
private String availability;
public Stock(int warehouseNumber, String productName, double price, int count, String availability) {
this.warehouseNumber = warehouseNumber;
this.productName = productName;
this.price = price;
this.count = count;
this.availability = availability;
}
public void setWarehouseNumber(int warehouseNumber) {
this.warehouseNumber = warehouseNumber;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setPrice(double price) {
this.price = price;
}
public void setCount(int count) {
this.count = count;
}
public void setAvailability(String availability) {
this.availability = availability;
}
public int getWarehouseNumber() {
return warehouseNumber;
}
public String getProductName() {
return productName;
}
public double getPrice() {
return price;
}
public int getCount() {
return count;
}
public String getAvailability() {
return availability;
}
#Override
public String toString() {
return "Warehouse number: " + this.warehouseNumber + ". Product name: " + this.productName + ". Price: " + this.price + ". Count: " + this.count + ". Availability of goods in stock" + this.availability;
}
}
Main file code:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Formatter;
public class Main extends Frame {
public static void main(String[] args) {
Frame mainWindow = new Main();
mainWindow.setTitle("Variant #1, Dudchenko Yaroslav, Group IT92-0/2");
mainWindow.setVisible(true);
mainWindow.setLayout(null);
mainWindow.setResizable(false);
mainWindow.setSize(1000, 600);
mainWindow.setLocation(400, 200);
Frame addFrame = new addGoodsWindow();
Frame deleteFrame = new deleteGoodsWindow();
Frame changeFrame = new changeGoodsWindow();
Button changeGoods = new Button("Change");
changeGoods.setBounds(150, 40, 140, 50);
mainWindow.add(changeGoods);
changeGoods.addActionListener(arg0 -> changeFrame.setVisible(true));
Button deleteGoods = new Button("Delete");
deleteGoods.setBounds(290, 40, 140, 50);
mainWindow.add(deleteGoods);
deleteGoods.addActionListener(arg0 -> deleteFrame.setVisible(true));
Button addGood = new Button("Add");
addGood.setBounds(10, 40, 140, 50);
mainWindow.add(addGood);
TextArea outputWindow = new TextArea();
outputWindow.setBounds(10, 90, 980, 500);
mainWindow.add(outputWindow);
outputWindow.setEditable(false);
addGood.addActionListener(arg0 -> addFrame.setVisible(true));
Button showGoods = new Button("View product list");
showGoods.setBounds(430, 40, 140, 50);
mainWindow.add(showGoods);
showGoods.addMouseListener(new MouseAdapter() {
Dialog dialog;
// Вывод списка продуктов
#Override
public void mouseClicked(MouseEvent e) {
ArrayList<Stock> stocks = null;
try {
stocks = readFromFile();
} catch (IOException ioException) {
System.out.println(ioException);
}
outputWindow.append("Product list:\n");
int i = 1;
for (Stock Stock :
stocks) {
outputWindow.append(i + ". " + Stock.toString() + "\n");
i++;
}
}
//Считывание с файла
public ArrayList<Stock> readFromFile() throws IOException {
Dialog dialog;
ArrayList<Stock> stocks = new ArrayList<>();
try {
FileInputStream fileInputStream = new FileInputStream("database.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Stock object;
try {
while ((object = (Stock) objectInputStream.readObject()) != null) {
stocks.add(object);
}
} catch (EOFException | ClassNotFoundException e) {
}
fileInputStream.close();
objectInputStream.close();
return stocks;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(mainWindow, "File not found");
}
return stocks;
}
});
// Очистка екрана
Button clearTextarea = new Button("Clear window");
clearTextarea.setBounds(870, 40, 120, 50);
mainWindow.add(clearTextarea);
clearTextarea.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
outputWindow.setText("");
}
});
//Сохранение в файл
Button saveSearch = new Button("Save data");
saveSearch.setBounds(570, 40, 160, 50);
mainWindow.add(saveSearch);
saveSearch.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
File file = new File("savesearch.txt");
Formatter formatter = null;
try {
formatter = new Formatter(file);
formatter.format(outputWindow.getText() + "\n");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} finally {
formatter.close();
}
}
});
mainWindow.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
File code for adding a product to a file:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class addGoodsWindow extends Frame {
public addGoodsWindow() throws HeadlessException {
String mainTitle = "Add goods";
Frame thisWindow = this;
setTitle(mainTitle);
setSize(300, 460);
setLocation(800, 360);
setVisible(false);
setLayout(null);
setResizable(false);
Label warehouseNumber = new Label("Warehouse number (required)");
warehouseNumber.setBounds(65, 30, 180, 30);
add(warehouseNumber);
TextField warehouseNumberInput = new TextField(1);
warehouseNumberInput.setBounds(10, 60, 280, 30);
add(warehouseNumberInput);
Label productName = new Label("Name of good (required)");
productName.setBounds(65, 100, 180, 30);
add(productName);
TextField productNameInput = new TextField(1);
productNameInput.setBounds(10, 130, 280, 30);
add(productNameInput);
Label price = new Label("The price of the product (required)");
price.setBounds(65, 170, 180, 30);
add(price);
TextField priceInput = new TextField(1);
priceInput.setBounds(10, 200, 280, 30);
add(priceInput);
Label count = new Label("Quantity of goods in stock (required)");
count.setBounds(65, 240, 200, 30);
add(count);
TextField countInput = new TextField(1);
countInput.setBounds(10, 270, 280, 30);
add(countInput);
Label availability = new Label("Availability (required)");
availability.setBounds(90, 310, 140, 30);
add(availability);
CheckboxGroup availabilityInput = new CheckboxGroup();
Checkbox availabilityInput1 = new Checkbox("In stock", availabilityInput, false);
availabilityInput1.setBounds(70, 340, 60, 40);
Checkbox availabilityInput2 = new Checkbox("Not availability", availabilityInput, false);
availabilityInput2.setBounds(150, 340, 90, 40);
add(availabilityInput1);
add(availabilityInput2);
Button buttonAddGoods = new Button("Add");
buttonAddGoods.setBounds(80, 380,140, 50);
add(buttonAddGoods);
buttonAddGoods.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Dialog dialog;
Checkbox checkbox = availabilityInput.getSelectedCheckbox();
try {
if (warehouseNumberInput.getText().length() != 0) {
if (productNameInput.getText().length() != 0) {
if (priceInput.getText().length() != 0) {
if (countInput.getText().length() != 0) {
if (checkbox != null) {
int warehouseNumber = Integer.parseInt(warehouseNumberInput.getText());
String productName = productNameInput.getText();
double price = Double.parseDouble(priceInput.getText());
int count = Integer.parseInt(countInput.getText());
String availability = checkbox.getLabel();
Stock obj = new Stock(warehouseNumber, productName, price, count, availability);
try {
File file = new File("database.txt");
FileOutputStream fileOutputStream;
ObjectOutputStream objectOutputStream;
if (file.exists()) {
fileOutputStream = new FileOutputStream(file, true);
objectOutputStream = new resetHeaderFile(fileOutputStream);
} else {
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
}
objectOutputStream.writeObject(obj);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException exception) {
}
warehouseNumberInput.setText("");
productNameInput.setText("");
priceInput.setText("");
countInput.setText("");
JOptionPane.showMessageDialog(thisWindow, "Add is success!");
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, check availability!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter count (integer value)!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter price!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter product name!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter warehouse number!");
}
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(thisWindow, "Type error!");
}
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
}
}
See also full list of errors:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.iterator()" because "stocks" is null
at com.company.Main$1.mouseClicked(Main.java:68)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6629)
at java.desktop/java.awt.Component.processEvent(Component.java:6391)
at java.desktop/java.awt.Button.processEvent(Button.java:390)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

I can't populate a JComboBox with an ArrayList

I have two classes, one has an ArrayList called "clanovi" which is populated by data from SQL database and I want to display that data in the "clanComboBox" in another class. I have been trying for two days but I can't figure it out.
Class with the list:
String cnnString;
String user;
String password;
public ArrayList<String> clanovi = new ArrayList<String>();
public ArrayList<String> getList(){
return clanovi;
}
public void Connect(String cnnString, String user, String password){
this.cnnString = cnnString;
this.user = user;
this.password = password;
ResultSet res = null;
try {
Connection connection = DriverManager.getConnection(cnnString, user, password);
System.out.println("Connection successful");
Statement stm = connection.createStatement();
String sql = "select Ime, Prezime from Clanovi";
res = stm.executeQuery(sql);
while(res.next()) {
clanovi.add(res.getString("Ime") + " " + res.getString("Prezime"));
}
System.out.println(clanovi);
} catch (SQLException e) {
System.out.println("An unexpected error occurred.");
e.printStackTrace();
}
}
The GUI class with the combobox:
public class PosuditiFilmFrame implements ActionListener{
SQLConnection con = new SQLConnection();
JFrame posuditiFilmFrame = new JFrame();
JButton posuditiFilmButton = new JButton();
JComboBox clanoviComboBox = new JComboBox();
JComboBox filmoviComboBox = new JComboBox();
JLabel clanLabel = new JLabel("Clan:");
JLabel filmLabel = new JLabel("Film:");
ArrayList<String> cBox = con.getList();
PosuditiFilmFrame(){
posuditiFilmButton = new JButton();
posuditiFilmButton.setBounds(200, 270, 200, 50);
posuditiFilmButton.addActionListener(this);;
posuditiFilmButton.setText("Posuditi Film");
posuditiFilmButton.setFocusable(false);
clanLabel.setBounds(50, 50, 70, 50);
clanLabel.setFont(new Font("Arial", Font.PLAIN, 25));
filmLabel.setBounds(50, 125, 70, 50);
filmLabel.setFont(new Font("Arial", Font.PLAIN, 25));
clanoviComboBox.setBounds(150, 50, 300, 50);
filmoviComboBox.setBounds(150, 125, 300, 50);
posuditiFilmFrame.setTitle("Posuditi Film");
posuditiFilmFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
posuditiFilmFrame.setLayout(null);
posuditiFilmFrame.setSize(600, 400);
posuditiFilmFrame.setVisible(true);
posuditiFilmFrame.add(posuditiFilmButton);
posuditiFilmFrame.add(clanoviComboBox);
posuditiFilmFrame.add(filmoviComboBox);
posuditiFilmFrame.add(clanLabel);
posuditiFilmFrame.add(filmLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==posuditiFilmButton) {
JOptionPane.showMessageDialog(null, "Film je posuden");
}
}
Of course, I also want the data to be displayed in that combobox

how to dedug in eclipse and solve Unknown Source erros

/*this is my java code which when i compile they don not show exactly error */
public class Login {
public JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conections;
private JTextField textField;
private JPasswordField passwordField;
public Login() {
initialize();
conections = SqliteConnectio.dbConnection();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 581, 411);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(266, 112, 193, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnLOGIN = new JButton("LOGIN");
Image jn=new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLOGIN.setIcon(new ImageIcon(jn));
btnLOGIN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select *from customer.sqlite where username=? and password=? ";
PreparedStatement pre = conections.prepareStatement(query);
pre.setString(1, textField.getText());
pre.setString(2, passwordField.getText());
ResultSet res = pre.executeQuery();
int count = 0;
while (res.next()) {
count++;
}
if (count == 1) {
JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
} else if (count > 1) {JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
}
else {
JOptionPane.showInternalMessageDialog(null, "username and password has been failed to be entered");
}
res.close();
pre.close();
} catch (Exception e) {
JOptionPane.showInternalMessageDialog(null, "you have failed to asses the database");
}
}
});
btnLOGIN.setBounds(321, 256, 125, 36);
frame.getContentPane().add(btnLOGIN);
JLabel userNAME = new JLabel("USERNAME");
userNAME.setBounds(156, 127, 85, 14);
frame.getContentPane().add(userNAME);
JLabel passLABEL = new JLabel("PASSWORD");
passLABEL.setBounds(156, 191, 85, 14);
frame.getContentPane().add(passLABEL);
passwordField = new JPasswordField();
passwordField.setBounds(266, 188, 193, 20);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("New label");
Image im=new ImageIcon(this.getClass().getResource("/login.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(im));
lblNewLabel.setBounds(10, 21, 136, 205);
frame.getContentPane().add(lblNewLabel);
}
}
//this is my connection to database which it seems to work just fine by prompting "username and password has sucseeful inserted"
package mi;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SqliteConnectio {
Connection conect=null;
public static Connection dbConnection(){
try {
Class.forName("org.sqlite.JDBC");
Connection conect=DriverManager.getConnection(
"jdbc:sqlite:E:\\JAVA WORLD\\sgliteDatabase\\customer.sqlite");
JOptionPane.showMessageDialog(null, "sucessful login to database");
return conect;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, "failed to login in database");
return null;
}
}
}

generating a unique string on pressing JButton and storing it into database table

I need to generate sequential number between 0-9 and want to display it in the JTextfield combined with the value from JCombobox(i.e.element of jcombobox+count)
as a string after pressing the JButton
When I select the first value from combobox and press the JButton the count should start from 0 and again when the second element from the combobox is selected the count should again start from 0 for second element and this should be the case for all other element of combobox.
For example-- when element 1 is selected and button is pressed the combined output should be 10,11,12,13... but,if in between this element 2 is selected
the output displayed in textfield should again start from 0 i.e.20,21,22...
and for element 3 the count should again start from 0 i.e. 30,31,32...
The combined output should be displayed in textfield
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Test extends JFrame implements ActionListener {
JButton b1, b2;
JComboBox jc;
String name;
JTextField t1;
Connection con, conn;
Statement st;
PreparedStatement pst;
ResultSet rs, rs1;
Test() {
setLayout(null);
JLabel l1 = new JLabel("USER SELECTION :");
l1.setBounds(100, 100, 150, 60);
add(l1);
jc = new JComboBox();
jc.setBounds(230, 114, 120, 30);
jc.addItem("SELECT");
jc.addActionListener(this);
add(jc);
JButton b1 = new JButton("GENERATE PART NO. :");
b1.setBounds(70, 340, 170, 30);
b1.addActionListener(this);
add(b1);
t1 = new JTextField(10);
t1.setBounds(270, 340, 200, 30);
add(t1);
JButton b2 = new JButton("BACK");
b2.setBounds(190, 420, 120, 30);
b2.addActionListener(this);
add(b2);
setSize(500, 500);
setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select Userdata from user1";
rs = st.executeQuery(s);
while (rs.next()) {
String name = rs.getString("Userdata");
jc.addItem(rs.getString("Userdata"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("GENERATE PART NO. :")) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
rs = st.executeQuery(s);
t1.getText();
if (rs.next()) {
String add1 = rs.getString("value");
t1.setEditable(false);
t1.setText("B" + add1);// B is the default value here which
// is also concatenated
}
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
if (str.equals("BACK") == true) {
new categ();
setVisible(false);
}
}
public static void main(String[] args) throws IOException {
Test td = new Test();
}
}

I cannot insert value in the table using textfield

I need to create a program in which values can be inserted using textfield in Java.
database getting connected ...
bt Cannot insert values using JTextfield ....need help..
shows error ..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;
JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;
public YouTubeTest()
{
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(null);
add(t1 = new JTextField(30));
t1.setBounds(10,10,200,50);
add(t2 = new JTextField(30));
t2.setBounds(10, 100, 200, 50);
add(l1 = new JLabel("First Name : "));
l1.setBounds(220, 10, 200, 50);
add(l2 = new JLabel("Last Name : "));
l2.setBounds(220, 100, 200, 50);
add(b1 = new JButton("Submit"));
b1.setBounds(10, 400, 60, 60);
add(b2 = new JButton("Clear"));
b2.setBounds(100, 400, 60, 60);
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
System.out.println("Database Connected Succesfully ..... ");
stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");
}catch(Exception e){
e.printStackTrace();
}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
try{
Fname = t1.getText();
Lname = t2.getText();
stmt.setString(1, Fname);
stmt.setString(2, Lname);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t1.setText("");
t2.setText("");
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
setVisible(true);
}
public static void main(String[] args)throws Exception {
new YouTubeTest();
}
};

Categories