my action performed doesnt work and it compile easily - java

i'm just making a assignment that connect database to jFrame and i need some help with this. i already try to compile the java and thats ok, but when i press the button nothing happen.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Assignment extends JFrame implements ActionListener{
JLabel label, l1, l2, l3, l4, l5;
JButton Add,Delete,Update,Display,Exit;
JTextField tf1, tf2, tf3, tf4, tf5;
Connection conn = null;
Statement stmt = null;
/**
* Create the frame.
*/
Menu() {
setVisible(true);
setSize(500, 500);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JDBC");
label = new JLabel("Database"); //Label
Add = new JButton("Add Data"); //Button
Delete = new JButton("Delete Data");
Update = new JButton("Update Data");
Display = new JButton("Display Data");
Exit = new JButton("Exit");
tf1 = new JTextField(); //textfield
tf2 = new JTextField();
tf3 = new JTextField();
tf4 = new JTextField();
/**
* Set bounds.
*/
Add.addActionListener(this);
Delete.addActionListener(this);
Update.addActionListener(this);
Display.addActionListener(this);
Exit.addActionListener(this);
/**
* add frame.
*/
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Add")){ //i already clicked on the button but it doesnt works
Add();
}
else if(e.getActionCommand().equals("Delete")){} //i havent code for this
else if(e.getActionCommand().equals("Update")){}
else if(e.getActionCommand().equals("Display")){}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
}
/**
* Create the second frame.
*/
public void Add() {
JFrame frm = new JFrame();
frm.setVisible(true);
frm.setSize(500, 500);
frm.setLayout(null);
frm.setTitle("JDBC");
l1 = new JLabel("ID : "); //Label
l2 = new JLabel("Name : ");
l3 = new JLabel("Adress : ");
l4 = new JLabel("Gender : ");
l5 = new JLabel("IP : ");
/**
* Set bounds.
*/
/**
* add frames.
*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/academic", "root", "abc"); //connecting
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO student VALUES(" +
"'" + tf1.getText() + "'," +
"'" + tf2.getText() + "'," +
"'" + tf3.getText() + "'," +
"'" + tf4.getText() + "'," +
tf5.getText() + ")";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String args[]) {
new Menu();
}
}
any idea guys ? please help me

You should be setting Action Command for your button
Add = new JButton("Add Data"); //Button
Add.setActionCommand("Add");
Same way for other buttons as well

in main method when you say new Menu(), its creating an instance of Java.awt.Menu, if you need to call the menu() method in your code, you need to use Assignment instance and call Menu() method.

Related

Adding JList to show basic DB information

My goal is to put a JList with the data from my DB over the 2 JTextFields, but i dont know how to do it. Do you guys and girls know what the mistake is and how I can fix it?
(The Variable personList has all the Data in it. Just need to put it in JList. But this Variable personList is a ArrayList.)
public class Datenbank2 extends JFrame {
public Datenbank2() {
super("Datenbank der Lehrlinge 1 Lehrjahr");
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel linkesPanel = new JPanel();
this.setBounds(600, 300, 500, 450);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager
.getConnection("jdbc:sqlite:C://Users/N-YP/workspace/UebungJava/ch/nyp/uebungen/datenbanken/SqLiteDB.db");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Person");
ArrayList<JLabel> personList = new ArrayList<JLabel>();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
personList.add(new JLabel(vorname + " " + nachname));
System.out.println(vorname + " " + nachname);
}
JTextField eingVorname = new JTextField();
JTextField eingNachname = new JTextField();
eingVorname.setPreferredSize(new Dimension(230, 30));
eingNachname.setPreferredSize(new Dimension(230, 30));
BorderLayout borderLayout = new BorderLayout();
this.getContentPane().setLayout(borderLayout);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
centerPanel.add(linkesPanel, BorderLayout.WEST);
FlowLayout flowLayout = new FlowLayout();
centerPanel.setLayout(flowLayout);
for (JLabel personLabel : personList) {
centerPanel.add(personLabel);
}
southPanel.setLayout(flowLayout);
southPanel.add(eingVorname);
southPanel.add(eingNachname);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(0);
System.out
.println("Datenbank geöffnet (muss später aber wieder geschlossen werden).");
}
}
public static void main(String[] args) {
Datenbank2 javamitdb = new Datenbank2();
javamitdb.setVisible(true);
}
}
Thank you and have a nice Day.
Well use DefaultListModel and its addElement() method in your while loop to add each result, like the following:
listModel = new DefaultListModel();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
listModel.addElement(vorname + " " + nachname);
System.out.println(vorname + " " + nachname);
}
//then create a list with this model
list = new JList(listModel);
Take a look at How to Use Lists for further information.

Give a layout that suits the components

I'm struggling to give a good layout to my Swing components. Currently FlowLayout being is used, but it doesn't look pretty. My requirement is to display the label l0 in top line. Then the label l1, combobox c1 and button b1 in second column (center aligned). Finally, the output that gets displayed in Jtable beneath. How do I do this?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search_1 extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table = new JTable();;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
JMenuBar menu = new JMenuBar();
r_search_1()
{
frame1 = new JFrame("yippee");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new FlowLayout());
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
frame1.add(l0);
frame1.add(l1);
//frame1.add(b1);
frame1.setVisible(true);
frame1.setSize(1000, 400);
try
{
File dbFile = new File("executive_db.accdb");
String path = dbFile.getAbsolutePath();
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
while (rs.next())
{
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setEditable(true);c1.setSelectedItem("");
c1.setBounds(150, 110, 150, 20);
frame1.add(c1);
frame1.add(b1);
st.close();
rs.close();
} catch (Exception e) {
}
// setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData()
{
// frame1 = new JFrame("Database Search Result");
// frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//frame1.setLayout(new FlowLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
String section_name = "";
String report_name = "";
String contact_name = "";
String link = "";
try
{
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
section_name = rs.getString("Section_Name");
report_name = rs.getString("Report_Name");
contact_name = rs.getString("Contact_Name");
link = rs.getString("Link");
model.addRow(new Object[]{section_name, report_name, contact_name, link});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
// frame1.setSize(1000, 400);
//table.close()
}
public static void main(String args[]) {
new r_search_1();
}
}
This is my requirement:
Notes
It is named PoorlySpecifiedLayout because you forgot the part about.. "and (if resizable) with extra width/height."
The UI is naturally taller than seen above. It was shortened to make a better screenshot.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class PoorlySpecifiedLayout {
// the GUI as seen by the user (without frame)
JPanel ui = new JPanel(new BorderLayout(5,5));
String[] comboValues = {
"String to pad combo."
};
String[] tableHeader = {
"Section Name","Report Name","Contact","Link"
};
String[][] tableBody = {{"", "", "", ""}};
PoorlySpecifiedLayout() {
initUI();
}
public final void initUI() {
ui.setBorder(new EmptyBorder(20,20,20,20));
JPanel top = new JPanel(new BorderLayout(15, 5));
ui.add(top, BorderLayout.PAGE_START);
top.add(new JLabel(
"Fetching search results", SwingConstants.CENTER));
JPanel controls = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 5));
top.add(controls, BorderLayout.PAGE_END);
controls.add(new JLabel("Search:"));
controls.add(new JComboBox(comboValues));
JButton submit = new JButton("submit");
Insets padButton = new Insets(5,20,5,20);
submit.setMargin(padButton);
controls.add(submit);
JTable table = new JTable(tableBody, tableHeader);
ui.add(new JScrollPane(table));
}
public final JComponent getUI(){
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
PoorlySpecifiedLayout psl = new PoorlySpecifiedLayout();
JFrame f = new JFrame("Poorly Specified Layout");
f.add(psl.getUI());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Edit: as per advice by Andrew Thompson - a picture.
Here is an example of how to do it using BorderLyout for the search / submit row and table, and adding the title in a border title instead of a label:
public class Search extends JFrame {
private final static String TITLE = "Fetching Search Results";
private final static String[] COLUMN_HEADERS = {"Section name", "Report name", "Contact", "Link"};
private final static String[] SEARCH_OPTIONS = {"AAAAA", "BBBBB"};
Search() {
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), TITLE, TitledBorder.CENTER, TitledBorder.TOP, new Font("Arial", Font.PLAIN, 20), Color.RED));
JPanel topPanel = new JPanel();
JLabel searchLabel = new JLabel("Search:");
JComboBox<String> searchBox = new JComboBox<>(SEARCH_OPTIONS);
JButton submitButton = new JButton("Submit");
topPanel.add(searchLabel);
topPanel.add(searchBox);
topPanel.add(submitButton);
JTable table = new JTable(new String[34][4], COLUMN_HEADERS);
mainPanel.add(topPanel, BorderLayout.PAGE_START);
mainPanel.add(new JScrollPane(table));
setContentPane(mainPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
new Search();
}
}
If you want the title as a label, you can put another panel for it.

make search result appear in the same page (Swing program)

So, this is a program in swing for implementing a search functionality. It runs perfectly well. No problems there. My requirement is to make the search results appear beneath the same page. In this code, I have made the results to appear in a new Jframe that opens a new window. I basically don't want this. I want to make the search result appear in the same page. So, should I modify the code ? Any form of help is appreciated. :) Thanks !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search_1 extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
Vector v = new Vector();
r_search_1()
{
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);
add(b1);
try
{
File dbFile = new File("executive_db.accdb");
String path = dbFile.getAbsolutePath();
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
while (rs.next())
{
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setEditable(true);c1.setSelectedItem("");
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
String section_name = "";
String report_name = "";
String contact_name = "";
String link = "";
try
{
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
section_name = rs.getString("Section_Name");
report_name = rs.getString("Report_Name");
contact_name = rs.getString("Contact_Name");
link = rs.getString("Link");
model.addRow(new Object[]{section_name, report_name, contact_name, link});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search_1();
}
}
Do not use Null layout. Use a BorderLayout.
All your search functionality should be in the center panel.
add(mySearchPanel, BorderLayout.CENTER);
Your results should be in the south panel. That way it will not shrink the center panel.
add(myResultsPanel, BorderLayout.SOUTH);
If there is nothing in the south panel, then it will shrink away making it seem like it is not there.
So, going into a little more detail, your l0,l1, and b1 components should go into a panel (say myTopPanel), and be added to the center. Your scroll component should be added to the bottom panel.
setTitle("Search Executive Reports ");
setLayout(new BorderLayout());
myTopPanel.add(l0);
myTopPanel.add(l1);
myTopPanel.add(b1);
add(myTopPanel, BorderLayout.CENTER)
add(scroll, BorderLayout.CENTER)

ActionListener not working with all of the objects

I have a problem that when I create a scrollpane with panels in them that are objects I want to add a button to every panel that when I click on it it will return the name of the product and put it in a variable. Problem is that it is only the last object panel in the scrollpane that gets connected to the Action Listener. Here is the code for the scrollpane and individual panels:
try{
System.out.println(sql);
ResultSet rs = data.SQL.executeQuery(sql);
String list = "";
int count=0;
while (rs.next()){
count++;
}
ResultSet result = data.SQL.executeQuery(sql);
ProductDisplayPanel.removeAll();
JPanel addPanel = new JPanel();
addPanel.setLayout(new GridLayout (count, 1));
JScrollPane scroll = new JScrollPane();
while (result.next()) {
searchDisplay = new SearchDisplay (result);
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
ProductDisplayPanel.add(scroll);
ProductDisplayPanel.revalidate();
ProductDisplayPanel.repaint();
System.out.println(list);
SearchDisplay.AddToCart.addActionListener(action);
frame.add(SearchDisplay.AddToCart);
} catch (Exception ae){
ae.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
Class that creates the actual panels:
public SearchDisplay(ResultSet result) throws Exception{
setPreferredSize(new Dimension(500, 156));
setVisible(true);
String link = result.getString("image");
System.out.println(link);
BufferedImage icecream = ImageIO.read( new URL( "file:///"+link));
JLabel lblImage = new JLabel(new ImageIcon (icecream));
name = result.getString("Name");
JLabel lblName = new JLabel(name);
String category = result.getString("Pieces");
JLabel lblFlavour = new JLabel("Pieces: "+category);
String productID = result.getString("ProductID");
JLabel lblPrice = new JLabel("Product ID: " + productID);
String price = result.getString("Price");
JLabel lblType = new JLabel("Price: "+ price +" kr");
String age= result.getString("Age");
JLabel lblBrand = new JLabel("Age: "+age);
AddToCart = new JButton("Add to cart");
I'm just not sure how you expected this to work...
You create a series of SearchDisplays and add them to the scroll pane (via the addPanel)
while (result.next()) {
searchDisplay = new SearchDisplay (result);
// nb- Bad idea
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
// nb- Worrisome...
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
Then you seem to add a single ActionListener to the some static object
SearchDisplay.AddToCart.addActionListener(action);
What's the connection? How does this AddToCart button know what it should be adding? Do you set some other static variable in the process??
I would imagin that every instance of SearchDisplay would have it's own AddToCart and it would have it's own ActionListener which knew which item it was associated with...

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