GUI / ActionListener麻烦

时间:2018-04-20 18:09:46

标签: java swing user-interface actionlistener

我为我的数据库程序制作了一个GUI,并且我试图创建一个按钮来预先创建数据库的删除功能。我遇到了ActionListener类的问题,并收到了一个名为

的错误

无法访问类型为delete的封闭实例。必须使用delete类型的封闭实例限定分配(例如x.new A(),其中x是delete的实例)。

代码第34行。我得到的另一个错误是

showDialogBu​​tton无法解析为变量

代码的第65行。任何帮助修复我的代码都将非常感激。

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);
}
}
}

1 个答案:

答案 0 :(得分:1)

阅读代码中的注释,以获得有关正在发生的事情的一些提示。

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();
            }
        }
    }
}

编辑:我只关注你想做什么以及你是如何做到的。如果需要,请检查以下内容。再次阅读代码中的注释以了解更多信息。

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();
        }
    }
}