I get an error "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JPasswordField
at def3.password$MyActionListener.actionPerformed(password.java:103)"
in the following code, what am I doing wrong?

static class MyActionListener implements ActionListener {

       	 private String userInput = "username";
       	 private static final String passText = "password" ; 
       	 JFrame frame ;
       	 MyActionListener(JFrame f){
       		 frame = f;
       	 }

           public void actionPerformed(ActionEvent e) {
        	   //JTextField userInput = (JTextField) e.getSource();
           >>> JPasswordField passInput = (JPasswordField) e.getSource(); <<<
               //String username = userInput.getText();
               char[] pass = passInput.getPassword();
               String password = new String(pass);
               
               if (/*username.equals(loginText) &&*/ password.equals(passText)) {
                  JOptionPane.showMessageDialog(null, "Corerect");
                  frame.getContentPane().setBackground(Color.blue);
               }
               else {
                    JOptionPane.showMessageDialog(null, "Wrong Login Details");
                   //frame.getContentPane().setBackground(Color.red);

               }
           }

At a guess that actionListener is attached to a JButton, yes?
So e.getSource() returns the source of the action, which is your JButton
You then try to cast it to a (JPasswordField), and that's illegal. You can't convert a button to a password field.
What you need there is to access the password field that was declared in you main form/window somewhere (code not posted, so I can't say more)

If I do that I will only be able to press enter and not the actual button, no?

Its a little messy, I know...

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

class MyWindowListener extends WindowAdapter {

    public void windowClosing(WindowEvent e) {
        System.out.println("Closing window!");
        System.exit(0);
    }
}

public class password {

//private static final String loginText =  "username";
//public String passText = "password";
   public static void main(String[] args) {
        JFrame frame = new JFrame("SimpleSwingExample");
        JPanel jp = new JPanel();
        jp.setBackground(Color.green);
        frame.setContentPane(jp);
        //frame.add(jp);
        JPanel logpnl = new JPanel();

        JLabel loginLabel = new JLabel("login : ");
        JTextField loginText = new JTextField(15);
        JLabel passLabel = new JLabel("password : ");
        JPasswordField passText = new JPasswordField(8);

        
        JButton loginBtn = new JButton(" Login ");
        frame.getContentPane().add(loginBtn);
        loginBtn.addActionListener(new MyActionListener(frame));
        logpnl.add(loginBtn, BorderLayout.SOUTH);
        
        Container c = new Container();
        c.setLayout(new BoxLayout(c,BoxLayout.X_AXIS));
        c.add(loginLabel);
        c.add(loginText);

        Container space = new Container();
        space.setLayout(new BoxLayout(space,BoxLayout.X_AXIS));
      
        
        //Container space3 = new Container();
        //space3.setLayout(new BoxLayout(space3,BoxLayout.X_AXIS));
        //space3.add(space2);


        Container d = new Container();
        d.setLayout(new BoxLayout(d,BoxLayout.X_AXIS));
        d.add(passLabel);
        d.add(passText);

        Container e = new Container();
        e.setLayout(new BoxLayout(e,BoxLayout.Y_AXIS));
        e.add(loginBtn);
       


        //logpnl.setLayout(new BoxLayout(logpnl, BoxLayout.Y_AXIS));
       
        logpnl.add(c);
        //logpnl.add(space);
        logpnl.add(d);
       // logpnl.add(space3);
          logpnl.add(e);
      

        frame.getContentPane().add(logpnl, BorderLayout.NORTH);

        // register an event handler for frame events

        

        frame.addWindowListener(new MyWindowListener());
        //frame.addActionListener(new ActionListener());
        frame.setSize(550, 520);
        frame.setVisible(true);


        frame.pack();
        
   }static class MyActionListener implements ActionListener {

       	 private String userInput = "username";
       	 private static final String passText = "password" ; 
       	 JFrame frame ;
       	 MyActionListener(JFrame f){
       		 frame = f;
       	 }

           public void actionPerformed(ActionEvent e) {
        	   //JTextField userInput = (JTextField) e.getSource();
               JPasswordField passInput = (JPasswordField) e.getSource();
               //String username = userInput.getText();
               char[] pass = passInput.getPassword();
               String password = new String(pass);
               
               if (/*username.equals(loginText) &&*/ password.equals(passText)) {
                  JOptionPane.showMessageDialog(null, "Corerect");
                  frame.getContentPane().setBackground(Color.blue);
               }
               else {
                    JOptionPane.showMessageDialog(null, "Wrong Login Details");
                   //frame.getContentPane().setBackground(Color.red);

               }
           }
        }
    }

what you're doing wrong? you're trying to cast a JButton to a JPasswordField

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JPasswordField

I assume what you are trying to do is, validate the info in your JPasswordField?
in that case:
you'll need to have a JPasswordField (let's call it pField), so then you can say:

public void actionPerformed(ActionEvent e) {
String inputted = pField.getText();
if ( inputted.equals(passText))
  System.out.println("Password correct");
else
  System.out.println("Wrong password!!!");

EDIT: give your variable to verify the password against another name than your JPasswordField

If I do that I will only be able to press enter and not the actual button, no?

do what?

Looking at the whole code your structure is causing the problem. You declare everything inside the main method, then you can't access them anywhere else - eg to read the password field in the action listener.

The normal way to do this is:
Declare fields etc inside the class but outside any method, so all methods can access them.
Make your listener classes inner classes so they have access to those fields as well.
Either make everything static (quick way out, but lousy Java technique) or have everything (except main) non-static, and just use main to create a new instance of your class by calling its constructor, where you set everything up.

Member Avatar for hfx642

Sounds like the OP wants to have a JPasswordField, and a JButton.
When the user presses (clicks) the Button, it should validate the Password Field.
Put an ActionListener on the Button to get the value in the Password Field, and process it accordingly.
Put a similar ActionListener on the Password Field, in case the user presses Enter instead of your Button.

Like this?

class LoginForm extends JFrame implements ActionListener {
	
	JFrame frame;
	JPanel jPanel;
	JLabel loginLabel;
	JTextField loginText;
	JLabel passLabel;
	JPasswordField passText;
	JButton loginBtn;
	
	{
	frame = new JFrame("SimpleSwingExample");
    jPanel = new JPanel();
    jPanel.setBackground(Color.green);
    frame.setContentPane(jPanel);
    loginLabel = new JLabel("login : ");
    loginText = new JTextField(10);
    passLabel = new JLabel("password : ");
    passText = new JPasswordField(10);
    loginBtn = new JButton(" Login ");
	
    frame.getContentPane().add(loginBtn);
    //loginBtn.addActionListener(new MyActionListener);
    frame.getContentPane().add(loginBtn, "SOUTH");
    
    passText.addActionListener(this);

    //Container c1 = new Container();
    //c1.setLayout(new BoxLayout(c1, BoxLayout.X_AXIS));
    frame.getContentPane().add(loginLabel, "NORTH");
    jPanel.add(loginText);
           
    //Container c2 = new Container();
    //c2.setLayout(new BoxLayout(c2,BoxLayout.X_AXIS));
    jPanel.add(passLabel);
    jPanel.add(passText);

    //Container c3 = new Container();
    //c3.setLayout(new BoxLayout(c3,BoxLayout.Y_AXIS));
    jPanel.add(loginBtn);
  
    //jPanel.add(c1);
    //jPanel.add(c2);
    //jPanel.add(c3);
	}


          public void actionPerformed(ActionEvent e) {
       	   //JTextField userInput = (JTextField) e.getSource();
              JPasswordField passInput = (JPasswordField) e.getSource();
              //String username = userInput.getText();
              char[] pass = passInput.getPassword();
              String password = new String(pass);
              
              if (/*username.equals(loginText) &&*/ password.equals(passText)) {
                 JOptionPane.showMessageDialog(null, "Corerect");
                 frame.getContentPane().setBackground(Color.blue);
              }
              else {
                   JOptionPane.showMessageDialog(null, "Wrong Login Details");
                  //frame.getContentPane().setBackground(Color.red);

              }
          }
}


 



public class LoginTester {

//private static final String loginText =  "username";
//public String passText = "password";
   public static void main(String[] args) {
        
        //JPanel logpnl = new JPanel();

        
       
      
        // register an event handler for frame events
	   LoginForm frame = new LoginForm();
	   frame.addWindowListener(new MyWindowListener());
        frame.setSize(480, 400);
        frame.setVisible(true);

        //frame.pack(); NEED???
        
           }
    }

Now I just get an empty frame...

no, we were talking about lines like:

JPasswordField passInput = (JPasswordField) e.getSource();

don't declare a JPasswordField on method level, declare it on class level.
and then you can do (for instance:)

public void actionPerformed(ActionEvent e) {
String password = passInput.getText();
// rest of your code
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.