ClassCastException: javax.swing.JButton

21,359

Solution 1

i hope this will help you.

public class PasswordForm {

    private static String password = "mypass";
    private JTextField usernameInput;

    public PasswordForm() {
    }

    private void init(){
         // Basic form create
        JFrame frame = new JFrame("Form 1");
        frame.setSize(300,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Creating the grid
        JPanel panel = new JPanel(new GridBagLayout());
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        GridBagConstraints c = new GridBagConstraints();

        // Create some elements
        usernameInput = new JTextField(10);
        c.gridx = 0;
        c.gridy = 1;
        panel.add(usernameInput,c);

        JPasswordField passwordInput = new JPasswordField(10);
        c.gridx = 0;
        c.gridy = 2;
        panel.add(passwordInput,c);

        JButton loginInput = new JButton("Login");
        c.gridx = 0;
        c.gridy = 3;
        loginInput.addActionListener(new LoginButton());
        panel.add(loginInput,c);


        frame.setVisible(true);
    }
    public static void main(String[] args){
       PasswordForm form = new PasswordForm();
       form.init();
    }

    class LoginButton implements ActionListener{

        public void actionPerformed(ActionEvent e){
            //JTextField usernameInput = (JTextField)e.getSource();
            String username = (usernameInput.getText().length()>0?usernameInput.getText():" U have not entered!");
            JOptionPane.showMessageDialog(null,"Text is : "+username);
        }
    }
}

Solution 2

The following exception happens when you ignore the fact that your code has compilation errors and try to run it anyway. (I assume that you are using Eclipse. Look for red error markers on the relevant source file, and check the Problems view.)

    Exception in thread "AWT-EventQueue-0" java.lang.Error: 
        Unresolved compilation problem:
        The method getText() is undefined for the type ActionEvent

The strange thing is that the embedded compilation error message doesn't seem to correspond to the source code that you posted. Either you've changed the code or some flaw in your build process is resulting in you running stale class files.


A couple of other points:

  • You are violating Java's naming conventions in your nested class. Class names should always start with a capital letter. Change "loginButton" to "LoginButton".

  • Your PasswordForm class is making too much use of static. The static inner class is OK, but declaring password as static, and putting all of your logic into the static main method will lead to problems in the long term. (OK, this code is clearly experimental ... in its current form.)

Solution 3

Not sure, but:

  1. JButton loginInput = new JButton("Login");
  2. JTextField usernameInput = (JTextField)e.getSource();

How could the source of the event be a TextField? It would be the JButton that the event originated from. You need to redesign this and your error will go away or become clearer.

Also, what Stephen C said: the error you've provided does not match your code.

PS : As to your question, as a lazy Java developer I would simply declare my userid field and password field on the class-level and then access those fields directly from the event. It is not the perfect way but acceptable for a beginner in Java.

Solution 4

This is an addendum to @tomdemuyt's answer, since I just ran your code really quickly. I got a totally different error to what you have:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JTextField
    at StupidCode$loginButton.actionPerformed(PasswordForm.java:54)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    ...more stack trace information that I'm not sure will help at this stage

The exception that I've gotten was just literally a copy-paste of your code into Eclipse, plus adding in necessary imports. So, as @Stephen pointed out earlier, you must have some problem in your build process or if you haven't changed anything, then perhaps your project setup is incorrect?


Edit:

Alright, well I can make the code do what you want. It's just that the code doesn't seem to come out very nicely, and there's already an over-reliance on static classes/methods as pointed out by Stephen. Hopefully, this is just experimental code that you're using to learn Java...

If you make the JPasswordField private and static, ie.

private static JPasswordField passwordInput;
//main method below
//...
//main method finished, action listener follows...

outside of the main method, then your ActionListener, loginButton can "see" it. This way, you could do something like

JOptionPane.showMessageDialog(null,"Text is: "+ new String(passwordInput.getPassword()));

But this isn't really a very nice way of constructing your class. It has all the flaws Stephen pointed out, and probably more because I'm not a great coder myself. It just should do what you want if you're wanting to hack something out really quickly.

Solution 5

I just want a simple dialog box when i press that button showing password, in C# would be easy, but not java ..

This is probably as easy in Java as it is in C#, but you are just more familiar with one language. I for starters have no clue how to get this done in C#. Anyway, I slightly modified your code to get it working (and I removed the non-relevant parts for the fix to keep my answer short)

public class PasswordForm {
 private static String password = "mypass";
 public static void main(String[] args){
  //Swing operations should happen on the EDT
  EventQueue.invokeAndWait( new Runnable(){
        public void run(){
           //whole UI creation
           final JTextField usernameInput = new JTextField(10);
           final JPasswordField passwordInput = new JPasswordField(10);
           //more UI creation
           JButton loginInput = new JButton("Login");
           loginInput.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
               JOptionPane.showMessageDialog(null,"Username is:" + usernameInput.getText() + " Password is:" + passwordInput.getText());
             }
           });
        }
      } //todo catch the exceptions from the invokeAndWait call
  }
}
Share:
21,359
Master345
Author by

Master345

Updated on July 10, 2020

Comments

  • Master345
    Master345 almost 4 years

    All I want is to make a simple user password login.

    I have put there an ActionListener and when I press log in just pop up the password and check if it's good.

    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    
    public class PasswordForm 
    {
        private static String password = "mypass";
        public static void main(String[] args)
        {
            // Basic form create
            JFrame frame = new JFrame("Form 1");
            frame.setSize(300,300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            // Creating the grid
            JPanel panel = new JPanel(new GridBagLayout());
            frame.getContentPane().add(panel, BorderLayout.NORTH);
            GridBagConstraints c = new GridBagConstraints();
    
            // Create some elements
            JTextField usernameInput = new JTextField(10);
            c.gridx = 0;
            c.gridy = 1;
            panel.add(usernameInput,c);
    
            JPasswordField passwordInput = new JPasswordField(10);
            c.gridx = 0;
            c.gridy = 2;
            panel.add(passwordInput,c);
    
            JButton loginInput = new JButton("Login");
            c.gridx = 0;
            c.gridy = 3;
            loginInput.addActionListener(new LoginButton());
            panel.add(loginInput,c);
    
    
            frame.setVisible(true);
        }
    
        static class LoginButton implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                JTextField usernameInput = (JTextField)e.getSource();
                JOptionPane.showMessageDialog(null,"Text is:");
            }
        }
    }
    

    Anyone with help?

    error

        Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton
    at PasswordForm$LoginButton.actionPerformed(PasswordForm.java:56)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    
  • Master345
    Master345 over 12 years
    i have only warnings like private static String password = "mypass"; is not used ... and i get that error, same error, i mean it ..
  • Master345
    Master345 over 12 years
    interesting ... hmm, but how do i solve this problem? i mean when i press LoginButton to pop-up an dialog box with the password. I really need to learn java, even though it's evil with me ...
  • Master345
    Master345 over 12 years
    i get it ... but how do i solve this problem? i mean when i press LoginButton to pop-up an dialog box with the password. I really need to learn java, even though it's evil with me ...
  • Master345
    Master345 over 12 years
    Ok, i reedited my post, mayby you're right, but i have not copy/paste-ed the code in eclipse, i'm trying to do this youtube.com/watch?v=1G8H8uAAsLo&feature=channel_video_title that believe me, even "copy/pasted" don't work. I just want a simple dialog box when i press that button showing password, in C# would be easy, but not java ...
  • Stephen C
    Stephen C over 12 years
    @RowMinds - "... even though it's evil with me". An attitude like that is not going to help you learn. "... in C# would be easy, but not java". Either use C#, or stop whinging.
  • Stephen C
    Stephen C over 12 years
    @RowMinds - "...... and i get that error, same error, i mean it". In that case, the problem must be that you are running a stale version of the class; i.e. one that did have that error when you compiled it.
  • Master345
    Master345 over 12 years
    so are you saying that code should actually working? maybe my Eclipse it's messed up, i see what i can do ... thanks ...
  • Stephen C
    Stephen C over 12 years
    I'm saying that code that has no compilation errors should not fail with a runtime error saying that it has compilation errors. You said there are no compilation errors. I cannot see how that 2 line method can have that particular compilation error. Now you do the reasoning. Something about your build process is messed up. It might be Eclipse. It might be something else.
  • Master345
    Master345 over 12 years
    if it is "Eclipse" or "something else" and not myself, that means i'm a little bit screwed, i will install Eclpise on my other computer, but i tell you, this is very STRNGE that "has compilation errors", btw, are you aware that i'm getting that error when i press Login button, right? thanks
  • Stephen C
    Stephen C over 12 years
    @RowMinds - yes I am aware of that.
  • Master345
    Master345 over 12 years
    ok, what you made there is called an "anonymous inner class" right? is this the right way? i mean it would be nice that every function to be one under other, and in a different file.class, i believe it's more elegant and ordered, but thanks :)
  • Master345
    Master345 over 12 years
    ok, but why i can't call JOptionPane.showMessageDialog(null,"Text is: "+ new String(passwordInput.getPassword())); from static class LoginButton implements ActionListener ?? From inside of static class .....
  • Master345
    Master345 over 12 years
    wow, this work, so, the method to get values outside the "class LoginButton implements ActionListener{ ....." is just put "(" and ")" for example if i want passwordInput i go String password = (passwordInput.getText()); where "(" and ")" from the left and right helps me get values outside the class LoginButton, right? Hope you understood me
  • Robin
    Robin over 12 years
    If you want to have the ActionListener in a separate class, you will have to pass those text fields to it.
  • Robin
    Robin over 12 years
    No, it works because class LoginButton is an inner class of the PasswordForm class, and can access the fields of its class. If you want to access the passwordInput, you will have to create a field for it
  • Master345
    Master345 over 12 years
    and that's a problem for me, you know ... :)) i understood from the last post below that if you want to get values outside the "class LoginButton implements ActionListener{ ....." is just put "(" and ")" for example if i want passwordInput i go String password = (passwordInput.getText()); where "(" and ")" from the left and right helps me get values outside the class LoginButton, right? Hope you understood me
  • Master345
    Master345 over 12 years
    and i also observed that your code is a little bit modified, i tryied for example to put one more Test and didn't succeeded, i get a real time error, here is the code text-upload.com/read.php?id=252035&c=3544300 ... btw, sorry to bother you, but i'm having a hard time getting the decent communication between me and java, hope it will pass
  • Robin
    Robin over 12 years
    I already answered that in another comment. What you need to do is start studying some basic Java concepts, for example this article about passing parameters to a constructor, scope rules or this SO question on scoping rules. So just learn some basic Java before bothering too much with Swing
  • blahman
    blahman over 12 years
    I'm sorry, I don't quite understand what you're asking? You should be able to call this if you externalise the JPasswordField to being outside your main method. Having said that, I don't think the way that you were constructing the code in your question was a very safe way of coding. Robin's suggestion to read the articles might help there. Were you getting an error when you tried calling that method?
  • Master345
    Master345 over 12 years
    when i click, it pops up in the log, the program keeps running
  • blahman
    blahman over 12 years
    If you want the program to exit upon the correct password being entered, you just need to check if the password is correct and then call System.exit(0), right? I'm sure that there's a more elegant solution, and I vaguely remember System.exit(0) being unsafe (maybe that was a different language) but I think that'd be the general guide to getting it to exit? Unless I'm misunderstanding your problem? (I might be, I wasn't very sure what you were asking...)