0

Coming from a non-typical coder, I need a little bit of assistance. I want to add a second JButton within the f1 section that I can code to run system.exit(0) to kill the program after the password has been confirmed. I got just about everything I need figured out except writing a 2nd JButton using a separate ActionListener. I'm just trying to write this as a secondary authorization program after the Windows login that I can pull passwords from a local SQL database. Any help would be much appreciated.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class Login extends JFrame implements ActionListener {
    JLabel l1, l2, l3;
    JTextField tf1;
    JButton btn1;
    JPasswordField p1;

    Login() {
        setTitle("Company Name");
        setVisible(true);
        setSize(525, 300);
        setLayout(null);

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1 = new JLabel("Enter Credentials:");
        l1.setForeground(Color.blue);
        l1.setFont(new Font("Serif", Font.BOLD, 20));

        l2 = new JLabel("Enter User Number:");
        l3 = new JLabel("Enter Password:");
        tf1 = new JTextField();
        p1 = new JPasswordField();
        btn1 = new JButton("Submit");

        l1.setBounds(100, 30, 400, 30);
        l2.setBounds(80, 70, 200, 30);
        l3.setBounds(80, 110, 200, 30);
        tf1.setBounds(300, 70, 200, 30);
        p1.setBounds(300, 110, 200, 30);
        btn1.setBounds(150, 160, 100, 30);

        add(l1);
        add(l2);
        add(tf1);
        add(l3);
        add(p1);
        add(btn1);
        btn1.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e) {
        showData();
    }

    public void showData() {
        JFrame f1 = new JFrame();
        JLabel l, l0;

        String str1 = tf1.getText();
        char[] p = p1.getPassword();
        String str2 = new String(p);
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp?user=root&password=password");
            PreparedStatement ps = con.prepareStatement("select name from emp where id=? and password=?");
            ps.setString(1, str1);
            ps.setString(2, str2);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                f1.setVisible(true);
                f1.setSize(525, 300);
                f1.setLayout(null);

                f1.setLocationRelativeTo(null);
                l = new JLabel();
                l0 = new JLabel("you are succefully logged in..");
                l0.setForeground(Color.blue);
                l0.setFont(new Font("Serif", Font.BOLD, 30));
                l.setBounds(60, 50, 400, 30);
                l0.setBounds(60, 100, 400, 40);

                f1.add(l);
                f1.add(l0);
                l.setText("Welcome " + rs.getString(1));
                l.setForeground(Color.red);
                l.setFont(new Font("Serif", Font.BOLD, 30));

            } else {
                JOptionPane.showMessageDialog(null, "Incorrect email-Id or password..Try Again with correct detail");
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public static void main(String arr[]) {
        new Login();
    }
} 
ryvantage
  • 13,064
  • 15
  • 63
  • 112
RMcK
  • 3
  • 1
  • The code is extremely spaced out so reading it is rather tedious. What is the issue exactly? Are you adding an action listener to your button? – Juxhin Aug 04 '14 at 21:03
  • Could you state your problem more specifically? – spoko Aug 04 '14 at 21:04
  • `setLayout(null);` See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Aug 04 '14 at 23:09
  • First off, thanks to all for the comments and suggestions. My apologizes on the code spacing and lack of detail on the question. I was writing this on my way out of the office yesterday and was in a bit of a hurry. – RMcK Aug 05 '14 at 11:50

3 Answers3

3

I'm not convinced that you really want to do this (although I could be wrong). If this is for a login window, and you kill the JVM with System.exit(...), then the whole program will end, including the code that called this login Window. Are you 100% sure that this is what you want to do?

Instead, I think that you wish to dispose of this window (which likely should be a JDialog and not a JFrame). Something like this code within an ActionListener could work:

public void actionPerformed(ActionEvent evt) {
  // get the button that was pressed
  AbstractButton src = (AbstractButton) evt.getSource();

  // get the top-level Window that holds the button
  Window window = SwingUtilities.getWindowAncestor(src);

  // dispose of this Window
  window.dispose();
}

Note, if the Window is a JFrame, and if it's defaultCloseOperation is set to JFrame.EXIT_ON_CLOSE, then this will also kill the JVM. If the JButton is instead held by a JDailog, then disposing the JDialog should not kill the JVM, but instead only close the JDialog and release its resources.


Edit
I agree with the others that your question as written is a bit unclear, and that your code is difficult to read due its formatting.

Other suggestions:

  • Avoid null layouts as they lead to very difficult to manage, debug, and improve GUI's.
  • Instead nest components, each using its own layout manager.
  • If you use layout managers, call pack() on your top-level GUI after adding components.
  • Don't call setVisible(true) on your top-level GUI until after adding components (and usually before calling pack()).
  • Read the Swing Tutorials for the details on how to code in Swing.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • To better clarify, I want to use this as a shell program after logging into Windows for two factor authentication. My goal is to have this program boot immediately after Windows login so that no other programs can be accessed until the user name and password is confirmed from the MySQL database. Since the showData() frame is what displays the successful login results, I wanted to have the secondary JButton with system.exit(0) coded to that window to kill the entire JVM so that the the system can be accessed. I hope that better describes the purpose. Let me know if more detail is needed. – RMcK Aug 05 '14 at 12:06
  • @RMcK: then my question is this, exactly what step has you stuck? If the problem is adding an ActionListener to another JButton, then user3803283's answer is correct (and I've already 1+ up-voted it). – Hovercraft Full Of Eels Aug 05 '14 at 12:12
2

If I'm understanding correctly, then the issue is that you are trying to have your Login class act as your action listener for the button.

Each button needs its own actionListener that defines its own actionPerformed method.

Considering what you want to do you can likely get away with having the button have an anonymous actionListener that you declare when you add it to the button as follows:

btn1.addActionListener(new ActionListener() 
{
     public void actionPerformed(ActionEvent e)
     {
         System.exit(0);
     }
});

However, as others have said, killing the JVM may not be what you really want.

Tyscribz
  • 136
  • 4
  • @HovercraftFullOfEels. This ended up working perfect. Thanks for the direction and thanks to user3803283 for the code. I would give 1+ if I were able to. – RMcK Aug 05 '14 at 14:14
0

I think I understand what you mean, but I might be wrong. You cannot have 2 ActionListeners. What you will have to do is make another JButton and add the same listener to it.

SOO:

  JButton BUTTON2 = new JButton(BUTTON2);
   BUTTON2.addActionListenter(this);

  Public void actionPerformed(ActionEvent e){

  if(e.getSource() == BUTTON2){
  System.exit(0);

  }else if(e.getSource() == BUTTON1){
    //Whatever you want in here
  }

  }
Nichos
  • 33
  • 2
  • 9
  • `"You cannot have 2 ActionListeners"` -- this is patently not true. Often Swing GUI's have multiple ActionListeners, often as anonymous inner classes. It is generally frowned upon to use the GUI or "view" class as its own listener, and doing this can lead to hard to debug and enhance "switch-board" listeners. – Hovercraft Full Of Eels Aug 04 '14 at 22:48
  • Thankyou, I did not know that. I am still a novice myself. – Nichos Aug 04 '14 at 23:09