I want that, if I click the buttons btnA1
and btnA2
the values like that (value A1 from btnA1 & value A2 from btnA2)
are added in an arraylist
. And after that when I click the Confirm
button the values of thearraylist
are will insert into mysql database.
MY code is given below:
public class bookseat extends JFrame {
private JPanel contentPane;
private JToggleButton btnA2;
private JToggleButton btnA1;
private JButton btnConfirm;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
bookseat frame = new bookseat();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public bookseat() {
initialize();
}
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < 200; i++) {
if (btnA1.getAction() != null) {
if (btnA1.isSelected()) {
arr.add("A1");
}
} else if (btnA2.getAction() != null) {
{
if (btnA2.isSelected()) {
arr.add("A2");
}
}
}
}
}
Connection con;
PreparedStatement pst;
ResultSet rs;
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/airline","root","");
}
catch(ClassNotFoundException ex) {
}
catch(SQLException ex) {
}
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnA1 = new JToggleButton("A1");
btnA1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(btnA1.isSelected()) {
String st = btnA1.getText();
arr.add(st);
}
}
});
btnA1.setBounds(10, 48, 67, 55);
contentPane.add(btnA1);
btnA2 = new JToggleButton("A2");
btnA2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(btnA2.isSelected()) {
String st = btnA2.getText();
arr.add(st);
}
}
});
btnA2.setBounds(87, 48, 67, 55);
contentPane.add(btnA2);
btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
pst = con.prepareStatement("insert into ticket_booking(Seats)values(?)");
for(int i=0; i < arr.size();i++){
pst.setString(1, arr.get(i).toString());
}
pst.executeUpdate();
}
catch(SQLException e1) {
}
}
});
btnConfirm.setBounds(35, 173, 89, 23);
contentPane.add(btnConfirm);
}
}
But my code looks wrong and give me null pointer.
java.lang.NullPointerException
at com.alpha.bookflight.bookseat.<init>(bookseat.java:183)
at com.alpha.bookflight.bookseat$1.run(bookseat.java:158)
java:183 line number is if (btnA1.getAction() != null)