Show MySQL data to JTextField - java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class RegistrationForm extends JFrame {
private JPanel panel;
private JLabel user,pass,id;
private JTextField user1,pass1,id1;
private JButton save,signIn;
public Connection con;
public Statement stm;
public PreparedStatement pstm;
public RegistrationForm(){
setTitle("Register Account");
setLayout(new FlowLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\RenRen\\Documents\\NetBeansProjects\\JavaConnector\\src\\images\\reg.jpg")));
JLabel sign = new JLabel("Sign Up:");
sign.setBounds(100,95,80,30);
sign.setFont(new Font("Login",Font.ITALIC,20));
id= new JLabel("User ID");
user = new JLabel("Username:");
pass = new JLabel("Password:");
JLabel acc = new JLabel("Already have an Account?");
id.setBounds(300,95,80,30);
user.setBounds(130,140,80,20);
pass.setBounds(250,140,80,20);
acc.setBounds(250,230,150,20);
id1 = new JTextField(5);
user1 = new JTextField(10);
pass1 = new JPasswordField(10);
id1.setBounds(350,100,80,20);
user1.setBounds(130,160,110,20);
pass1.setBounds(250,160,110,20);
save = new JButton("Save");
signIn = new JButton("Sign In");
save.setBounds(150,200,90,20);
signIn.setBounds(250,200,90,20);
add(sign);
add(id);
add(id1);
add(user);
add(user1);
add(pass);
add(pass1);
add(save);
add(signIn);
add(acc);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","");
stm=con.createStatement();
}
catch(Exception e)
{ JOptionPane.showMessageDialog(null, e);
}
ActionListener action = new ActionHandler();
save.addActionListener(action);
signIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null, "Thank You!");
dispose();
LoginMain LM = new LoginMain();
LM.run();
}});
}
private class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == save){
String sql="Insert into logform(username,password)values(?,?)";
try{
pstm = con.prepareStatement(sql);
pstm.setString(1, user1.getText());
pstm.setString(2, pass1.getText());
pstm.execute();
JOptionPane.showMessageDialog(null, "Saved!");
}catch(Exception se){
JOptionPane.showMessageDialog(null, "Save Failed");
}
}
}
}
public void run(){
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
RegistrationForm rf = new RegistrationForm();
rf.run();
}
}
I want to show a data from MySQL database to JTextField. For example, a data from UserID in MySQL database is 1, I want to show that data in JTextField, and they can't edit text in JTextField. Can anyone help me please?

if UserID is integer use this code
jTextField.setText(String.valueOf(UserID);
//This make jTextField not editable
jTextField.setEditable(false);

Related

Add data into MySQL Database using Eclipse

I tried to make a simple programming that allows student's data to be added, updated, deleted and viewed for my assignments. I'm already stuck at adding part. What is the correct syntax /code to use in order to insert data into the database?
I'm using Eclipse IDE software and XAMPP for this programming.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class PracticalExercise2 extends JFrame implements ActionListener{
Connection con;
Statement stmt;
JLabel lblname, lblmatricnumber, lblproject,lbltajuk;
JTextField txtname, txtmatricnumber , txtproject;
JButton btntest,btnadd,btnupdate,btndelete,btnview;
String user,pass;
ResultSet rs;
JTabbedPane myTab;
JPanel pnladd,pnlupdate,pnldelete,pnlview;
public PracticalExercise2() {
setLayout(null);
setSize(400,400);
setTitle("Registration Form using JTabbedPane");
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//GUI SETTING FOR FORM
lbltajuk = new JLabel("Registration Form");
lbltajuk.setBounds(10, 20, 350, 50);
lbltajuk.setFont(new Font("Arial",Font.BOLD,32));
lbltajuk.setForeground(Color.BLUE);
add(lbltajuk);
//JTabbedPane is also a panel
myTab = new JTabbedPane();
myTab.setBounds(20,70,350,200);
add(myTab);
pnladd = new JPanel();
pnlupdate = new JPanel();
pnldelete = new JPanel();
pnlview = new JPanel();
//Create and add Tab
myTab.addTab("Add Data", pnladd);
myTab.addTab("Update Data", pnlupdate);
myTab.addTab("Delete Data", pnldelete);
myTab.addTab("View Data", pnlview);
btntest = new JButton("Test Connection");
btntest.setBounds(120, 300, 150, 30);
add(btntest);
btntest.addActionListener(this);
add();
}
public static void main(String[] args) {
new PracticalExercise2();
}
void add()
{
pnladd.setLayout(null);
lblname = new JLabel("Nama :");
lblname.setBounds(20,20,100,30);
pnladd.add(lblname);
lblmatricnumber = new JLabel("No Matrik :");
lblmatricnumber.setBounds(20,60,100,30);
pnladd.add(lblmatricnumber);
lblproject = new JLabel("Projek :");
lblproject.setBounds(20,100,100,30);
pnladd.add(lblproject);
txtname = new JTextField();
txtname.setBounds(110,20,200,30);
pnladd.add(txtname);
txtmatricnumber = new JTextField();
txtmatricnumber.setBounds(110,60,200,30);
pnladd.add(txtmatricnumber);
txtproject = new JTextField();
txtproject.setBounds(110,100,200,30);
pnladd.add(txtproject);
btnadd = new JButton("Add Data");
btnadd.setBounds(120, 140, 100, 30);
pnladd.add(btnadd);
btnadd.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btntest)
{
// 1. load driver
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException x)
{
JOptionPane.showMessageDialog(null, "mySQL Driver cannot connect.");
}
// 2. create/open connection
try {
//testing the connection to database.
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicaltask2", "root", "");
JOptionPane.showMessageDialog(null, "No connection error.");
} catch (SQLException y) {
JOptionPane.showMessageDialog(null, "Connection error.");
}
}
if(e.getSource() == btnadd)
{
String name , matric , project;
name = txtname.getText();
matric = txtmatricnumber.getText();
project = txtproject.getText();
try {
PreparedStatement stmnt = con.prepareStatement("insert into pelajar(NULL,nama,nomatrik,projek)values(NULL,?,?,?)", Statement.RETURN_GENERATED_KEYS);
((PreparedStatement) stmt).setString(2,name);
((PreparedStatement) stmt).setString(3,matric);
((PreparedStatement) stmt).setString(4,project);
JOptionPane.showMessageDialog(null, "Record Added Successfuly");
txtname.setText("");
txtmatricnumber.setText("");
txtproject.setText("");
}
catch (Exception a)
{
JOptionPane.showMessageDialog(null, "Failed to add data");
}
}
}
}

How can I transfer data between one jframe to another jframe?

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

connecting JComboBox to JTextField [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have populated my JComboBox with the value of same database table and I need an idea to display the value of JComboBox as it is in JTextField.
I am not using Array list instead I am using database table(mysql),below is the program
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);
JComboBox jc = new JComboBox();
jc.setBounds(230,114,120,30);
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/d02","root","");
st = con.createStatement();
String s = "select Userdata from user";
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");
conn = DriverManager.getConnection("jdbc:mysql://localhost/d02","root","");
String query="select value from user where Userdata=?";
PreparedStatement pst=conn.prepareStatement(query);
String tmp=(String)jc.getSelectedItem().toString();
if(jc.getSelectedItem()!=null)
pst.setString(1,tmp);
ResultSet rs1=pst.executeQuery();
while(rs1.next())
{
String add=rs1.getString("value");
t1.setText(add);
}
}
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();
}
}
Add ItemListener to your JComboBox
jc.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cmbMyItemStateChanged(evt);
}
});
listener method:
private void cmbMyItemStateChanged(java.awt.event.ItemEvent evt){
String value = jc.getSelectedItem().toString();
if(jc.getSelectedItem()!=null){
}
}

How do I use CardLayout for my Java Program for Login and Menu Items

I am creating a "Store" program that basically can allow an employee to log in with a username and password I provide. After logging in, the employee can then see a "main menu" with four buttons: Sales Register, PLU Settings, Settings, and Logout. From this screen, the employee can proceed by clicking on any of the buttons to navigate to that screen. I do not want a new window to popup every time a button is clicked, but instead I want there to be some transition (or no transition) to go to the page that is clicked.
So to give an example: When the employee starts the program, he/she is greeted with the login menu. Then the employee enters his/her login information and hits login. If the info is incorrect, the employee is prompted to re-enter the info. If the info is correct, the employee is now sent to the main menu. At the main menu the employee selects "Sales Register" and the program goes to the sales register. All of this should happen in one window.
I have added the code of what I have been able to do, so far. I have created all of the buttons and labels, but I can't get them to show up on the JFrame and use the CardLayout. Also, I do not know how to link the Login code with the CardLayout.
Thank you for helping me. Here is the code:
Main Menu Code (storeMainMenu.java)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class storeMainMenu implements ActionListener {
String loginString = "Login";
String salesRegisterString = "Sales Register";
String pluSettingsString = "PLU Settings";
String settingsString = "Settings";
String logoutString = "Logout";
//JFrame
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
Color myColor = Color.decode("#F1E0B8");
//JPanel
static JPanel buttonPanel = new JPanel();
JPanel test1 = new JPanel();
JPanel test2 = new JPanel();
JPanel test3 = new JPanel();
JPanel test4 = new JPanel();
//Buttons
JButton salesRegister = new JButton("Sales Register");
JButton pluSettings = new JButton("PLU Settings");
JButton settings = new JButton("Settings");
JButton logout = new JButton("Logout");
//Label
JLabel header = new JLabel("Store Register");
JLabel test_1 = new JLabel("Test 1");
JLabel test_2 = new JLabel("Test 2");
JLabel test_3 = new JLabel("Test 3");
JLabel test_4 = new JLabel("Test 4");
public storeMainMenu ()
{
//Header
header.setFont(new Font("Myriad", Font.PLAIN, 50));
header.setBounds((width/6),0,1000,100);
//Sales Register Bounds
salesRegister.setBounds(100, 100, 500, 250);
//PluSettings Bounds
pluSettings.setBounds(700, 100, 500, 250);
//Settings Bounds
settings.setBounds(100, 500, 500, 250);
//Logout Bounds
logout.setBounds(700, 500, 500, 250);
//JPanel bounds
buttonPanel.setLayout(null);
//TEST JPANEL
test1.setLayout(null);
test2.setLayout(null);
test3.setLayout(null);
test4.setLayout(null);
test1.setSize(width, height);
test2.setSize(width,height);
test3.setSize(width, height);
test4.setSize(width, height);
//Test JPANEL Labels
test_1.setFont(new Font("Myriad", Font.PLAIN, 50));
test_1.setBounds((width/6),0,1000,100);
test_2.setFont(new Font("Myriad", Font.PLAIN, 50));
test_2.setBounds((width/6),0,1000,100);
test_3.setFont(new Font("Myriad", Font.PLAIN, 50));
test_3.setBounds((width/6),0,1000,100);
test_4.setFont(new Font("Myriad", Font.PLAIN, 50));
test_4.setBounds((width/6),0,1000,100);
//Adding to test JPanel
test1.add(test_1);
test2.add(test_2);
test3.add(test_3);
test4.add(test_4);
//Adding to JFrame
buttonPanel.add(header);
buttonPanel.add(salesRegister);
buttonPanel.add(pluSettings);
buttonPanel.add(settings);
buttonPanel.add(logout);
}
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = new CardLayout();
if (e.getSource() == salesRegister) {
cardLayout.show(test1, salesRegisterString);
}
if (e.getSource() == pluSettings) {
cardLayout.show(test2, pluSettingsString);
}
if (e.getSource() == settings) {
cardLayout.show(test3, settingsString);
}
if (e.getSource() == logout) {
cardLayout.show(test4, logoutString);
}
}
static void createAndShowGUI() {
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
Color myColor = Color.decode("#F1E0B8");
JFrame frame = new JFrame("Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(width, height);
frame.setBackground(myColor);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(buttonPanel);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Login Code (login.java):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class login extends JFrame {
//declaring our swing components
JLabel l_name,l_pass;
JTextField t_name;
JPasswordField t_pass; //A special JTextField but hides input text
JButton button;
Container c;
boolean checkLogin = false;
//a inner class to handling ActionEvents
handler handle;
//a separate class for processing database connection and authentication
database db;
login()
{
super("Login form");
c=getContentPane();
c.setLayout(new FlowLayout());
//extra classes
db=new database();
handle =new handler();
//swing components
l_name=new JLabel("Username");
l_pass=new JLabel("Password");
t_name=new JTextField(10);
t_pass=new JPasswordField(10);
button=new JButton("Login");
//adding actionlistener to the button
button.addActionListener(handle);
//add to contaienr
c.add(l_name);
c.add(t_name);
c.add(l_pass);
c.add(t_pass);
c.add(button);
//visual
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,175);
}
public static void main(String args[])
{
#SuppressWarnings("unused")
login sample=new login();
}
//an inner class .You can also write as a separate class
class handler implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
//checks if the button clicked
if(ae.getSource()==button)
{
char[] temp_pwd=t_pass.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);
//The entered username and password are sent via "checkLogin()" which return boolean
if(db.checkLogin(t_name.getText(), pwd))
{
//a pop-up box
JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
checkLogin = true;
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
checkLogin = false;
}
}//if
}//method
}//inner class
}
Database Code (the login code references this code for the MySQL info) (database.java)
import java.sql.*;
public class database
{
Connection con;
PreparedStatement pst;
ResultSet rs;
database()
{
try{
//MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
//ALSO SET THE CLASSPATH
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SchoolStoreUsers","root","schoolstore");
pst=con.prepareStatement("select * from users where uname=? and pwd=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
//ip:username,password
//return boolean
public Boolean checkLogin(String uname,String pwd)
{
try {
pst.setString(1, uname); //this replaces the 1st "?" in the query for username
pst.setString(2, pwd); //this replaces the 2st "?" in the query for password
//executes the prepared statement
rs=pst.executeQuery();
if(rs.next())
{
//TRUE iff the query founds any corresponding data
return true;
}
else
{
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error while validating"+e);
return false;
}
}
}
Stop using null layouts, seriously, this is the source of more problems then just about anything else with Swing
When adding components to a panel using CardLayout, each panel MUST have a name
In your actionPerformed method, this is not how CardLayout works. To start with, you're creating a new instance of CardLayout, which contains NO components, so how did you expect it to be able to suddenly figure out what to switch to? When using CardLayout#show, the component reference is the parent component that that is begin manged by the CardLayout
Updated with example
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyCardLayout {
public static void main(String[] args) {
new MyCardLayout();
}
public MyCardLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel mainPane;
private JPanel navPane;
private List<String> pages;
private int currentPage;
public TestPane() {
pages = new ArrayList<>(25);
setLayout(new BorderLayout());
mainPane = new JPanel(new CardLayout());
navPane = new JPanel();
for (int index = 0; index < 10; index++) {
addPageTo(mainPane, "Page" + index, new JLabel("Page " + index, JLabel.CENTER));
}
JButton btnPrev = new JButton("<<");
JButton btnNext = new JButton(">>");
navPane.add(btnPrev);
navPane.add(btnNext);
btnPrev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentPage(getCurrentPage() - 1);
}
});
btnNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentPage(getCurrentPage() + 1);
}
});
add(mainPane);
add(navPane, BorderLayout.SOUTH);
setCurrentPage(0);
}
public int getCurrentPage() {
return currentPage;
}
protected void setCurrentPage(int page) {
if (pages.size() > 0) {
if (page < 0) {
page = pages.size() - 1;
} else if (page >= pages.size()) {
page = 0;
}
currentPage = page;
CardLayout layout = (CardLayout)mainPane.getLayout();
layout.show(mainPane, pages.get(currentPage));
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void addPageTo(JPanel pane, String name, Component comp) {
pages.add(name);
pane.add(comp, name);
}
}
}

JDBC ODBC with MS Access issue

I want to store a record but don't know what to do.
When i start entering the details of a customer, at that time database connectivity is successfully created but I fail to store the data in the database.
The procedure is correct to create the database but I can't enter the details, what can I do?
Here is the code:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
//package p1;
public abstract class New_Customer extends JFrame implements ActionListener
{
JTextField textFieldId;
JTextField textFieldName;
JTextField textFieldContactNo;
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JComboBox combo;
String course[] = {"Navakal","SandhyaKal","Pudhari","MidDay","Inqlab","BusinessLine","Mumbai Samachar","GujrajSamachar","KarnatakMalla","Vartahar","PunyaNagari"};
JButton b1;
JButton b2;
Container c = getContentPane();
New_Customer()
{
super("Shree DattaDigambar Samarth");
setBounds(140,250,777,555);
c.setLayout(null);
textFieldId = new JTextField();
textFieldName = new JTextField();
textFieldContactNo = new JTextField();
l1 = new JLabel("New Customer Entry");
l2 = new JLabel("Building No");
l3 = new JLabel("Customer Name");
l4 = new JLabel("Contact No");
l5 = new JLabel("Paper");
combo = new JComboBox(course);
l1.setBounds(10,10,340,20);
l2.setBounds(10,20,140,70);
l3.setBounds(110,20,140,70);
l4.setBounds(300,50,140,20);
l5.setBounds(400,50,140,20);
textFieldId.setBounds(10,70,70,20);
textFieldName.setBounds(110,70,180,20);
textFieldContactNo.setBounds(300,70,90,20);
combo.setBounds(400,70,130,20);
b1 = new JButton("Add paper");
b2 = new JButton("Ok");
b1.setBounds(10,100,100,20);
b2.setBounds(10,160,50,20);
c.add(combo);
c.add(b1);
c.add(b2);
c.add(l1);
c.add(l2);
c.add(l3);
c.add(l4);
c.add(l5);
c.add(textFieldId);
c.add(textFieldName);
c.add(textFieldContactNo);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args)
{
New_Customer nc=new New_Customer() {};
}
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
if(e.getSource()==b1)
{
}
if(e.getSource()==b2)
{
try
{
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:devendra");
try
{
java.sql.Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement(null);
ResultSet rs = ps.executeQuery("insert into Customer values(?,?,?,?)");
while(rs.next())
{
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
}
catch (ClassNotFoundException | SQLException ee)
{
System.out.println("Error:connection not created");
}
}
}
}
First of all to insert values in database, you should use executeUpdate() method.
And this method does not return any ResultSet.
So Change your code
PreparedStatement ps = con.prepareStatement("insert into Customer values(?,?,?,?)");
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
ps.executeUpdate();

Categories

Resources