sir i want a program of all the layout of java which have two or three button and a database connectivity
Hi Friend,
Try the following code:
import java.awt.*; import java.sql.*; import javax.swing.*; import java.awt.event.*; class LayoutExample extends JFrame{ JPanel panel,panel1,panel2; JLabel lab1,lab2; JTextField text1,text2; JButton b1,b2,b3; LayoutExample(){ panel=new JPanel(); panel1=new JPanel(new GridLayout(2,2)); panel2=new JPanel(new FlowLayout()); lab1=new JLabel("Name"); lab2=new JLabel("Address"); text1=new JTextField(20); text2=new JTextField(20); b1=new JButton("Add"); b2=new JButton("View"); b3=new JButton("Delete"); panel1.add(lab1); panel1.add(text1); panel1.add(lab2); panel1.add(text2); panel2.add(b1); panel2.add(b2); panel2.add(b3); panel.add(panel1,BorderLayout.NORTH); panel.add(panel2,BorderLayout.SOUTH); add(panel); setVisible(true); setSize(500,150); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String v1=text1.getText(); String v2=text2.getText(); try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st=con.createStatement(); int i=st.executeUpdate("insert into data(name,address) values('"+v1+"','"+v2+"')"); JOptionPane.showMessageDialog(null,"Data is inserted successfully"); } catch(Exception ex){ } } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String v1=text1.getText(); String v2=text2.getText(); JFrame f=new JFrame(); JLabel l1=new JLabel("Your Name is : "+v1); JLabel l2=new JLabel("Your Address is : "+v2); l1.setBounds(20,20,200,20); l2.setBounds(20,50,200,20); f.setLayout(null); f.add(l1); f.add(l2); f.setVisible(true); f.setSize(300,200); } }); b3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String v1=text1.getText(); String v2=text2.getText(); try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st=con.createStatement(); int i=st.executeUpdate("delete from data where name='"+v1+"' and address='"+v2+"'"); JOptionPane.showMessageDialog(null,"Data is deleted successfully"); } catch(Exception ex){ } } }); } public static void main(String[] args) { new LayoutExample(); } }
Thanks
Ads