- Create a simple GUI using GridBagLayout
- Get input from the user to delete the corresponding record
- Delete a record from the database on pressing the button
We will delete a customer record from the database. User has to provide the customer account number in order to delete the customer. The program will contain a class for handling database transaction, one for creating the GUI and a driver program.
Here is the class that creates our GUI.
public class SimplePanel extends JFrame
{
JTextField accountNumber;
public SimplePanel()
{
setTitle("Delete record from Database");
accountNumber = new JTextField(10);
}
public void createAndDisplay()
{
JPanel panel = new JPanel(new GridBagLayout());
JPanel banner = new JPanel();
banner.add(new JLabel("Delete record from the database"), BorderLayout.CENTER);
banner.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
panel.add(banner, c);
JLabel label = new JLabel("Customer Account Number");
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
panel.add(label, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
panel.add(accountNumber, c);
JButton deleteBtn = new JButton("Delete");
deleteBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
CustomerHandler handler = new CustomerHandler();
try
{
handler.deleteCustomer(Integer.valueOf(accountNumber.getText()));
}
catch (Exception e)
{
e.printStackTrace(); // handle the exception in a better way. this is just an example
}
}
});
c.gridx = 0;
c.gridy = 3;
panel.add(deleteBtn, c);
this.getContentPane().add(panel);
pack();
setVisible(true);
}
}
Here is the output window from the above program
For the DBConnection class have a look at this post. And the handler that will actually delete the record from the database
public class CustomerHandler
{
public void deleteCustomer(int customerAccouontNumer) throws Exception
{
DBConnection db = new DBConnection();
Connection conn = db.getConnection();
Statement st = null;
// First check if the conn is null then throw an exception or handle in some other way
try
{
st = conn.createStatement();
st.execute("Delete from Customer where account_number = " + customerAccouontNumer + ";");
}
catch (Exception e1)
{
throw new Exception("Unable to delete customer!" + e1.getMessage());
}
finally
{
// close the connection and the statement
}
}
And the driver program
public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SimplePanel p = new SimplePanel();
p.createAndDisplay();
}
});
}
}
Remember to do the imports.
No comments:
Post a Comment