Я создаю графический интерфейс для своей программы базы данных и пытаюсь создать кнопку, которая выполняет функцию удаления для базы данных. У меня проблемы с классом ActionListener, и я получаю сообщение об ошибке
Нет доступных экземпляров типа delete. Должен квалифицировать выделение с помощью включающего экземпляра типа delete (например, x.new A (), где x - это экземпляр удаления).
в строке 34 кода. Еще одна ошибка, которую я получаю:
showDialogButton не может быть преобразован в переменную
в строке 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);
}
}
}




Прочтите комментарии внутри кода, чтобы получить представление о том, что происходит.
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();
}
}
}
и Эрик, пожалуйста, прочтите все комментарии. это хорошие предложения, которым вы должны следовать
@LonelyNeuron Спасибо за редактирование. Я тоже отредактировал пост, чтобы добавить еще один подход слушателя :)
Хороший пост не отмечает правки, но включает их;) meta.stackexchange.com/a/127655/316262
Это получило бы одобрение, если бы я не исчерпал свой дневной максимум голосов. Если вы @ упомянете меня в другой день, я проголосую за ваш ответ;)