简体   繁体   中英

Disposing JFrame with addActionListener using a JButton

I have been trying to solve ths problem for the past 3 days :/

I have a class Login() which creates a JFrame-object

Another class named LoginTab() which has a constructor with a JFrame-object as parameter.

I want to dispose the JFrame with a Button in the LoginTab() class. But the addActionListener does not accept the JFrame-object and I don't know why :(

The Code of the LoginTab():

package tabs;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

import abstractClasses.JTextFieldImmo;
import abstractClasses.ValidateInput;

import programs.MySQL;
import windows.ButtonPanel;
import windows.UserDetails;

public class LoginTab extends ValidateInput {

/**
 * 
 */
private static final long serialVersionUID = 1L;

static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);

// static Connection con = null;
static Statement stnt = null;
static ResultSet rs = null;

public LoginTab(JFrame window) {
    panelMethod(window);
}

// LOGIN ITEMS
JLabel usernameLbl = new JLabel(r.getString("username"));
JLabel passwordLbl = new JLabel(r.getString("password"));
JTextFieldImmo usernameFld = new JTextFieldImmo(10);
JPasswordField passwordFld = new JPasswordField(10);
JButton loginBtn = new JButton(r.getString("login"));
JButton registerUserBtn = new JButton("Neuer Benutzer"); // TODO String
                                                            // einfügen

public void panelMethod(JFrame window) {

    this.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();

    // Insets
    c.insets = new Insets(4, 5, 0, 0);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    this.add(usernameLbl, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 1;
    c.gridy = 0;
    this.add(usernameFld, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 1;
    this.add(passwordLbl, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 1;
    c.gridy = 1;
    this.add(passwordFld, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 1;
    c.gridy = 2;
    this.add(loginBtn, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 2;
    this.add(registerUserBtn, c);

    // Actions Listener


    loginBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                MySQL.connect();
                String username = usernameFld.getText().trim();
                String password = String.valueOf(passwordFld.getPassword())
                        .trim();

                String sql = "SELECT username,password from per_user where username = '"
                        + username + "'and password = '" + password + "'";
                stnt = MySQL.getCon().createStatement();
                rs = stnt.executeQuery(sql);

                int count = 0;

                while (rs.next()) {
                    count = count + 1;
                }

                if (count == 1) {
                    JOptionPane.showMessageDialog(null, "User Found, Access Granded!"); //TODO String
                    //window.setVisible(false);
                    //window.dispose();
                    new ButtonPanel();
                } else if (count > 1) {
                    JOptionPane.showMessageDialog(null,
                            "Duplicate User, Access Denied!"); // TODO String einfügen
                } else {
                    JOptionPane.showMessageDialog(null, "User not Found"); // TODO String einfügen
                }

            } catch (Exception e1) {
                // JOptionPane.showMessageDialog(null,
                // "Es konnte keine Verbindung zum MySQL Server hergestellt werden.");
                e1.printStackTrace();
            }

        }
    });

    registerUserBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new UserDetails();
        }
    });

    passwordFld.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            loginBtn.doClick();

        }
    });
}
}        

To call a method on another object, you need a reference to that other object. One problem I see with your code is that nowhere (that I can see anyway) is there a reference to your currently visualized Login object. To solve the problem, you will need to gain this reference, perhaps via a constructor parameter or a setter method, and then close the JFrame.

As an aside, it is somewhat unusual to have to close a JFrame in this fashion mid-program. Are you sure that you shouldn't instead be using a modal dialog such as a JDialog here in place of a JFrame?

Also, your code shows many GUI components, but where are they added to a top-level window and displayed?


Edit
Also note that you can get the enclosing top level Window via the SwingUtilities method:

SwingUtilities.getWindowAncestor(...);

Check out the ExitAction from Closing an Application . The ExitAction class will find the active window and then send a close request to that window. So the class can be used to close any window.

You need to make the reference to window as final in order to access it inside anonymous class ActionListener :

public void panelMethod(final JFrame window) {
    // obmitted code
}

And then:

loginBtn.addActionListener(new ActionListener() {
    // obmitted coce

    if (count == 1) {
    JOptionPane.showMessageDialog(null, "User Found, Access Granded!"); //TODO String
    window.setVisible(false);
    window.dispose();
    new ButtonPanel();
    }

    // ...
}

I would suggest you to read Core Java Volumn I in order to know the good approach to develop Java application as well as using Swing components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM