簡體   English   中英

ClassCastException:javax.swing.JButton

[英]ClassCastException: javax.swing.JButton

我只想做一個簡單的用戶密碼登錄。

我已經放了一個ActionListener ,當我按下登錄時,只需彈出密碼並檢查它是否正常。

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:");
        }
    }
}

有幫助的人嗎?

錯誤

    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)

當您忽略代碼有編譯錯誤並嘗試運行它的事實時,會發生以下異常。 (我假設你正在使用Eclipse。在相關的源文件中查找紅色錯誤標記,並檢查Problems視圖。)

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

奇怪的是嵌入式編譯錯誤消息似乎與您發布的源代碼不對應。 要么你改變了代碼,要么你的構建過程中的一些缺陷會導致你運行過時的類文件。


其他幾點:

  • 您違反了嵌套類中的Java命名約定。 類名應始終以大寫字母開頭。 將“loginButton”更改為“LoginButton”。

  • 您的PasswordForm類過多地使用static static內部類是可以的,但是將password聲明為靜態,並將所有邏輯放入靜態main方法中將導致長期問題。 (好吧,這段代碼顯然是實驗性的......目前的形式。)

我希望這能幫到您。

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);
        }
    }
}

不確定,但是:

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

事件的來源怎么可能是TextField 事件起源於JButton 您需要重新設計此錯誤,您的錯誤將消失或變得更加清晰。

此外,Stephen C所說的:您提供的錯誤與您的代碼不符。

PS:關於你的問題,作為一個懶惰的Java開發人員,我只需在類級別聲明我的userid字段和密碼字段,然后直接從事件中訪問這些字段。 它不是完美的方式,但對於Java初學者來說是可以接受的。

這是對@ tomdemuyt的答案的補充,因為我只是很快就運行了你的代碼。 我得到了一個完全不同的錯誤:

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

我得到的例外只是將代碼復制粘貼到Eclipse中,並添加了必要的導入。 所以,正如@Stephen先前指出的那樣,你的構建過程中一定有問題,或者如果你沒有改變任何東西,那么你的項目設置可能不正確?


編輯

好吧,我可以讓代碼做你想要的。 只是代碼看起來並不是很好,並且已經過度依賴斯蒂芬所指出的靜態類/方法。 希望這只是您用來學習Java的實驗代碼......

如果你使JPasswordField私有和靜態的,即。

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

在main方法之外,那么你的ActionListenerloginButton可以“看到”它。 這樣,你可以做類似的事情

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

但這並不是構建課程的一種非常好的方式。 它有斯蒂芬指出的所有缺陷,可能更多因為我自己不是一個偉大的編碼器。 do what you want if you're wanting to hack something out really quickly. 如果你想要快速破解某些東西,它做你想要的。

我只想要一個簡單的對話框,當我按下顯示密碼的按鈕時,在C#中會很容易,但不是java ..

這在Java中可能和在C#中一樣容易,但您只熟悉一種語言。 我對於初學者不知道如何在C#中完成這項工作。 無論如何,我稍微修改了你的代碼以使其工作(我刪除了修復的不相關部分以保持我的答案簡短)

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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM