JTextField无法正常工作

时间:2013-06-06 15:35:19

标签: java swing nullpointerexception jtextfield

我正在尝试使用getText()方法将用户输入存储到全局静态变量中。

userinput是JTextField,在createContentPane()

中初始化

我创建了一个访问器方法getText()来从JTextField获取用户输入并将其存储在名为words的静态变量中,但是我收到一条错误消息。

package Windows;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Ceaser_Cipher extends JFrame implements ActionListener
{
    private static JLabel titleLabel;
    private static JTextField userinput;
    private static JTextArea resultTA;
    private static JButton runButton, homeButton;
    private static String words;
    private static int key = 5;
    private static String cipherd;
    private static String decipherd;


    public static void createAndShowGUI()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] Ceaser_Cipher [=]");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 600);
        frame.setVisible(true);

        Ceaser_Cipher GUI = new Ceaser_Cipher();
        frame.setContentPane(GUI.createContentPane());
    }

    public JPanel createContentPane()

    {
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        JPanel titlepanel = new JPanel();
        titlepanel.setBackground(Color.pink);
        titlepanel.setLayout(null);
        titlepanel.setLocation(0, 0);
        titlepanel.setSize(500, 150);
        totalGUI.add(titlepanel);

        titleLabel = new JLabel("WELCOME to Ceaser's Cipher!!!!");
        titleLabel.setLocation(0, 0);
        titleLabel.setSize(500, 140);
        titleLabel.setHorizontalAlignment(0);
        titlepanel.add(titleLabel);

        JPanel textpanel = new JPanel();
        textpanel.setBackground(Color.red);
        textpanel.setLayout(null);
        textpanel.setLocation(0, 150);
        textpanel.setSize(500, 150);
        totalGUI.add(textpanel);

        userinput = new JTextField("Enter the word you want to ENCRYPT");
        userinput.setHorizontalAlignment(2);
        userinput.setLocation(100, 0);
        userinput.setSize(300, 140);
        textpanel.add(userinput);

        JPanel resultpanel = new JPanel();
        resultpanel.setBackground(Color.yellow);
        resultpanel.setLayout(null);
        resultpanel.setLocation(0, 300);
        resultpanel.setSize(500, 150);
        totalGUI.add(resultpanel);

        resultTA = new JTextArea();
        resultTA.setLocation(50, 0);
        resultTA.setSize(400, 140);
        resultpanel.add(resultTA);

        JPanel buttonpanel = new JPanel();
        buttonpanel.setBackground(Color.green);
        buttonpanel.setLayout(null);
        buttonpanel.setLocation(0, 450);
        buttonpanel.setSize(500, 200);
        totalGUI.add(buttonpanel);

        runButton = new JButton("RUN!");
        runButton.setLocation(200, 10);
        runButton.setSize(100, 30);
        runButton.addActionListener(this);
        buttonpanel.add(runButton);

        homeButton = new JButton("HOME!");
        homeButton.setLocation(200, 50);
        homeButton.setSize(100, 30);
        homeButton.addActionListener(this);
        buttonpanel.add(homeButton);

        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public void actionPerformed(ActionEvent evt)
    {
        Object src = evt.getSource();
        if (src == runButton)
        {
            resultTA.setText("\n" + "The ENCRYPTION key generated is " + key + "\n" + "ENCRYPTED text is " + cipherd
                    + "\n" + "DECRYPTED text is " + decipherd);
        }
        if (src == homeButton)
        {

        }
    }

    public static void main(String[] args) 
    {
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });
        }


        key = random();
        words = getText();
        cipherd = encrpt(words, key);
        decipherd = decrpt(cipherd, key);
    }



    private static String getText() 
    {
        String word = userinput.getText();

        return word;
    }

    public static String encrpt(String text, int key)
    {
        //Array containing all the alphabetical characters.
                char alphabets [] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                        'U', 'V', 'W', 'X', 'Y', 'Z'};

                //Array where the user's String will be inserted into and replaced with the ENCRYPTED characters.
                char plain [] = words.toUpperCase().toCharArray();
                //ENCRYPTION loop here, replaces the characters in the users String with the shifted alphabets based on the ENCRYPTION key.
                for (int i = 0; i < plain.length; i++)
                {
                    for (int j = 0; j < alphabets.length; j++)
                    {
                        if(plain[i] == alphabets[j])
                        {
                            plain[i] = alphabets[(j + key) % 26];
                            break;
                        }
                    }
                }

                String cipher = String.valueOf(plain);
                return cipher;
    }

    public static String decrpt(String text, int key)
    {
        //Array containing all the alphabetical characters.
        char alphabets [] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z'};
        char plain [] = words.toUpperCase().toCharArray();
        char cipherd [] = new char[100];
        //DECRYPTION loop here, gets the ENCRYPTED characters and replaces them with the original alphabets by reversing the ENCRYPTION key.
                for (int i = 0; i < plain.length; i++)
                {
                    for (int j = 0; j < alphabets.length; j++)
                    {
                        if(plain[i] == alphabets[j])
                        {
                            cipherd[i] = alphabets[(j - key + 26) % 26];
                            break;
                        }
                    }
                }

        String decipher = String.valueOf(cipherd);
        return decipher;    
    }

    public static int random()
    {
        //Random object created here.
        Random ran = new Random();
        //Random number between 1-3 is generated here.
        key = ran.nextInt(9) + 1;

        return key;
    }
}

3 个答案:

答案 0 :(得分:2)

调用JTextFielduserinput getText尚未初始化(因为它将在EDT中初始化),导致NullPointerException在这一行

String word = userinput.getText();

创建用户界面并检索EDT

中的文字

以下是的列表:

  • 请勿使用static语言(如Java。
  • )使用OO个变量
  • 请勿使用以大写字母开头的包名称。 Java命名约定使用小写作为包名称。
  • 不要扩展JFrame,创建实例并使用
  • 不要使用绝对定位(null布局),而是使用布局管理器

答案 1 :(得分:1)

问题是:

words = getText();,JTextField实例化之前调用userinput方法。因为,到时为null,您将获得NullPointerException

答案 2 :(得分:1)

您正在创建错误的框架。如果您已经使该课程扩展了JFrame,那么创建新的JFrame就没有意义了。将班级更改为

public class Ceaser_Cipher extends JFrame implements ActionListener
{

    // remove the keyword 'static' from the variables. it's not necessary.
    private JLabel titleLabel;
    private JTextField userinput;
    private JTextArea resultTA;
    private JButton runButton, homeButton;
    private String words;
    private int key = 5;
    private String cipherd;
    private String decipherd;

    // constructor.
    public Ceaser_Cipher()
    {
        // this class extends a JFrame. so you can call it's methods directly
        // and you do not need to create the frame again.

        super("[=] Ceaser_Cipher [=]");
        setCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 600);

        // set the content pane to the panel returned by your method.
        setContentPane(createContentPane());

        // avoid calculations in the main method. you may place them here.
        key = random();
        words = userInput.getText();
        cipherd = encrpt(words, key);
        decipherd = decrpt(cipherd, key);

        setVisible(true);
    }

    // Your createContentPane method. it's fine. copy it here.
    // Your actionPerformed method is also fine. copy it here.

    // And finally the main method.
    public static void main(String[] args)
    {
        // This calls the constructor and everything will be fine.
        new Ceaser_Cipher();
    }

}