Erik
Erik

Reputation: 15

GUI/ActionListener troubles

I'm making a GUI for my database program and I'm trying to create a button that preforms the delete function for the database. I'm having problems with the ActionListener class and getting an error called

No enclosing instance of type delete is accessible. Must qualify the allocation with an enclosing instance of type delete (e.g. x.new A() where x is an instance of delete).

on line 34 of the code. Another error I'm getting is

showDialogButton cannot be resolved to a variable

on line 65 of the code. Any help in fixing my code would be greatly appreciated.

import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class delete
{
static JFrame frame;

public static void main(String[] args)
{
    // schedule this for the event dispatch thread (edt)
    SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                displayJFrame();
            }
        });
}

static void displayJFrame()
{

    frame = new JFrame("Our JButton listener example");

    // create our jbutton
    JButton showDialogButton = new JButton("Click Me");

    // add the listener to the jbutton to handle the "pressed" event
    showDialogButton.addActionListener(listen);
}

public class MyActionListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
    // display/center the jdialog when the button is pressed

    try {
        Scanner scan = new Scanner(System.in);
        //System.out.println("Enter a table");
        String table = "teacherexample";
        //System.out.println("Enter a num");
        int num = 4;

        //Get connection to DB
        Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false" , "root" , "Starwars991211");
        String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
        PreparedStatement preparedStatement = myConn.prepareStatement(sql);  
        preparedStatement.executeUpdate(sql);


    }
    catch (Exception exc) {
        exc.printStackTrace();

    }

    // put the button on the frame
    frame.getContentPane().setLayout(new FlowLayout());
    frame.add(showDialogButton);

    // set up the jframe, then display it
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(300, 200));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
}
}

Upvotes: 0

Views: 56

Answers (1)

George Z.
George Z.

Reputation: 6808

Read the comments inside the code in order to get some hints of what is happening.

package test;

import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Delete { // Class names should start with an upper case letter.
    private JFrame frame; // Don't use a static JFrame (only if you know
                          // exactly what you are doing :))
    private JButton showDialogButton; // This must be a field if you wanna access it in 
                                      // another class, in your case, the listener.

    public static void main(String[] args) {
        // Schedule this for the event dispatch thread (edt)
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Delete del = new Delete(); // Create new instance of Delete class.
                del.displayJFrame(); //Call display method.
            }
        });
    }

    private void displayJFrame() {
        frame = new JFrame("Our JButton listener example");

        // Create our JButton
        showDialogButton = new JButton("Click Me");

        // Add the listener to the JButton to handle the "pressed" event
        showDialogButton.addActionListener(new MyActionListener());

        // Adding the button should be done outside of the ActionLister. If it is inside
        // the frame it will never be shown, because the Listener cannot be called 
        // (obviously) without a visible frame.
        frame.getContentPane().setLayout(new FlowLayout());
        // Add the button to the frame
        frame.add(showDialogButton);

        // Set up the JFrame, then display it
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(300, 200));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // display/center the JDialog when the button is pressed

            try {
                Scanner scan = new Scanner(System.in);
                // System.out.println("Enter a table");
                String table = "teacherexample";
                // System.out.println("Enter a num");
                int num = 4;

                // Get connection to DB
                Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
                        "root", "Starwars991211");
                String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
                PreparedStatement preparedStatement = myConn.prepareStatement(sql);
                preparedStatement.executeUpdate(sql);

            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }
}

Edit: I just gave attention to what you wanna do and how you try to do it. Give a check to the following if you want. Read comments inside the code again to understand more.

public class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // Display/center the JDialog when the button is pressed
        final String table = "teacherexample"; // Personal opinion: if something
                                               // wont change, define it final
        int num = 500; //Your number here, i guess from scanner input.
        String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
        // Since java 8, auto closable, read https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
        try (Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
                    "root", "Starwars991211");PreparedStatement preparedStatement = myConn.prepareStatement(sql);) 
        {
            preparedStatement.executeUpdate(sql);
        }
        catch (SQLException exc) { // Catching all exceptions is bad practice
                                   // catch only the exception you wait here...
            exc.printStackTrace();
        }
    }
}

Upvotes: 1

Related Questions