I'm having a problem with GUI. When I click on JButton b1, when the text is empty in the JTextField text it does not catch the exception.
The query is executing only once when the button is clicked,if clicked again it throws exception and query is not executing
Code:
public class A extends JFrame{
private JTextField text;
private JButton b1;
private JLabel l1;
private Connection conn;
private Statement state;
private ResultSet set;
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
//query enter in textfield | select * from universty.student where rollno=2
public A() throws ClassNotFoundException, SQLException{
super("Frame");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
getContentPane().setLayout(null);
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = text.getText();
set = state.executeQuery(query);
set.next();
String answer = set.getString(2);
l1.setText(answer);
}
catch (Exception e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
finally{
try{
set.close();
state.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
}
Main Method:
public class Main {
public static void main(String args[]) throws ClassNotFoundException, SQLException{
A obj = new A();
}
}
throwsin your main method has a really bad taste. Use your try/catch block to handle your exceptions.