-1

暗号化されたコードまたは暗号化されるコードの入力を取得するために JFileChooser と JPassword を使用するコードを作成しようとしています。

これが暗号化されるコードです。.rtf または .txt ファイルに保存します。キーは「アニー」です。出力は

"Fv '$zi (# pzm"| (wy& `%ip(zzm%".

プロジェクト「Password」の下に 2 つの異なるクラス ファイルがあります。1 つのクラスは「File Opener」と呼ばれます。クラスを「Password1」と呼びます。

これが Password1.java です。

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

/* PasswordDemo.java requires no other files. */

public class Password1 extends JPanel
                          implements ActionListener {
    private String key;
    private static String OK = "ok";

    private JFrame controllingFrame; //needed for dialogs
    private JPasswordField passwordField;

    public Password1(JFrame f) {
        //Use the default FlowLayout.
        controllingFrame = f;

        //Create everything.
        passwordField = new JPasswordField(10);
        passwordField.setActionCommand(OK);
        passwordField.addActionListener(this);

        JLabel label = new JLabel("Enter the key: ");
        label.setLabelFor(passwordField);

        JComponent buttonPane = createButtonPanel();

        //Lay out everything.
        JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        textPane.add(label);
        textPane.add(passwordField);

        add(textPane);
        add(buttonPane);
    }

    protected JComponent createButtonPanel() {
        JPanel p = new JPanel(new GridLayout(0,1));
        JButton okButton = new JButton("OK");
        okButton.setActionCommand(OK); 
        okButton.addActionListener(this);
        p.add(okButton);
        return p;
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        controllingFrame.dispose();

        if (OK.equals(cmd)) { //Process the password.
            char[] input = passwordField.getPassword();

            key = new String(input);
            //Zero out the possible password, for security.
            Arrays.fill(input,'0');
            passwordField.selectAll();
            resetFocus();
        } else {
            System.out.println("Please enter a key.");
        }
    }

    public String getKey(){
        return key;
    }

    //Must be called from the event dispatch thread.
    protected void resetFocus() {
        passwordField.requestFocusInWindow();
    }

    public static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Key");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        final Password1 newContentPane = new Password1(frame);
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Make sure the focus goes to the right component
        //whenever the frame is initially given the focus.
        frame.addWindowListener(new WindowAdapter() {
            public void windowActivated(WindowEvent e) {
                newContentPane.resetFocus();
            }
        });

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();
            }
        });
    }
}

そして、これが FileOpener.java です。

   import javax.swing.*;
import java.io.*;

import javax.swing.filechooser.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class FileOpener extends JPanel implements ActionListener {
    static private final String newline = "\n";
    private Password1 p1;
    JButton decodeButton, encodeButton;
    JFileChooser fc;
    JTextArea log;
    Scanner in = new Scanner(System.in);
    JFrame frame;
    File file;
    int count;

    public FileOpener(){
        // create and set up the window.
        frame = new JFrame("Open Your File");


        // make the program close when the window closes
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create the box layout
        frame.getContentPane( ).setLayout(new BoxLayout(frame.getContentPane( ), BoxLayout.Y_AXIS));

        //label prompting user for input
        JLabel label1 = new JLabel ("Would you like to encode or decode your file?", JLabel.CENTER);
        frame.getContentPane().add(label1);

        //create a filer chooser
        fc = new JFileChooser();

        // add a button object
        decodeButton = new JButton("Decode");
        decodeButton.addActionListener(this);
        frame.getContentPane( ).add(decodeButton);

        encodeButton = new JButton("Encode");
        encodeButton.addActionListener(this);
        frame.getContentPane( ).add(encodeButton);


        // display the window.
        frame.pack( );
        frame.setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {

        //Handle open button action.
        if (e.getSource() == encodeButton) {
             frame.dispose();
            int returnVal = fc.showOpenDialog(FileOpener.this);

            if (returnVal == JFileChooser.APPROVE_OPTION ) {

                try {
                    file = fc.getSelectedFile();
                    p1 = new Password1(frame);
                    p1.createAndShowGUI();
                    //get length of key
                    String key = p1.getKey();
                    int length3 = key.length();
                    count = 0;
                    int keyAsciiValues[] = new int[length3];
                    String name1 ="";
                    //get ascii value of each letter in key
                    for (int k=0; k<length3; k++){
                        char a = key.charAt(k);
                        int ascii1 = (int)a;
                        //put ascii value of letter in key to array
                        keyAsciiValues[k]= ascii1;

                    }

                    FileInputStream file2= new FileInputStream(file);

                    //create a scanner for it
                    in = new Scanner(file2);
                    //read in message
                    String name;
                    name = in.nextLine();
                    for (int k=0; k<length3; k++){
                        char a = key.charAt(k);
                        int ascii1 = (int)a;
                        //put ascii value of letter in key to array
                        keyAsciiValues[k]= ascii1;
                    }
                    //measure length of code message array
                    int length1 = name.length();
                    //measures length of strings in code message array
                    for(int j=0;j<length1;j++){
                        char c = name.charAt(j);
                        int ascii = (int)c;
                        ascii += keyAsciiValues[count];
                        if(c != ' '){
                            count++;
                        }
                        if(count>length3-1){
                            count = 0;
                        }
                        while(ascii>126){
                            ascii-= 93;
                        }
                        char b=(char)ascii;
                        if(c == ' '){
                            b = ' ';
                        }
                        name1 += b;
                    }
                    System.out.println(name1);


                } catch (FileNotFoundException k){
                    //the file was not found!
                    System.out.println("File could not be opened!");
                }
            }

            //Handle save button action.
        } else if (e.getSource() == decodeButton) {
             frame.dispose();
            int returnVal = fc.showOpenDialog(FileOpener.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                try {
                    file = fc.getSelectedFile();
                    p1 = new Password1(frame);
                    p1.createAndShowGUI();
                    //open the file

                    //get length of key 
                    String key = p1.getKey();
                    int length3 = key.length();
                    count = 0;
                    int keyAsciiValues[] = new int[length3];
                    String name1 ="";
                    //get ascii value of each letter in key
                    for (int k=0; k<length3; k++){
                        char a = key.charAt(k);
                        int ascii1 = (int)a;
                        //put ascii value of letter in key to array
                        keyAsciiValues[k]= ascii1;
                    }



                    //create a scanner for it
                    in = new Scanner(file);

                    //read in message
                    String name;
                    name = in.nextLine();
                    for (int k=0; k<length3; k++){
                        char a = key.charAt(k);
                        int ascii1 = (int)a;
                        //put ascii value of letter in key to array
                        keyAsciiValues[k]= ascii1;
                    }
                    //measure length of code message array
                    int length1 = name.length();
                    //measures length of strings in code message array
                    for(int j=0;j<length1;j++){
                        char c = name.charAt(j);
                        int ascii = (int)c;
                        ascii -= keyAsciiValues[count];
                        if(c != ' '){
                            count++;
                        }
                        if(count>length3-1){
                            count = 0;
                        }
                        while(ascii<33){
                            ascii+= 93;
                        }
                        char b=(char)ascii;
                        if(c == ' '){
                            b = ' ';
                        }
                        name1 += b;
                    }
                    System.out.print(name1);


                } catch (FileNotFoundException k){
                    //the file was not found!
                    System.out.println("File could not be opened!");
                }
            }

            in.close(); 

                log.append("Opening: " + file.getName() + "." + newline);
            }
    }


public static void main(String args[]) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
  FileOpener f = new FileOpener();
}    
}

JFileChooser と Password を追加する前は問題なく動作していました。別名、コードの実際の暗号化部分に問題はないはずです。

java.lang.NullPointerExceptionFileOpener の 70 行目に at 行が表示されます。

int length3 = key.length();

ありがとう!

4

1 に答える 1

2

createAndShowGUI()メソッドでは、インスタンスPassword1JFrameモーダルではなくで表示しますJDialog。したがって、この表示命令はノンブロッキングです。つまり、コードの実行を停止したり、ウィンドウを閉じるボタンをクリックするまで待機したりしません。

その結果、そのメソッドが属性を実行して初期化する前にPassword1インスタンスを取得するため、は静止しており、そのインスタンスで任意のメソッドを呼び出すと を取得します。keyactionPerformed()keykeynullNullPointerException

私の提案は、インターフェイスを管理するためにモーダルJDialogを使用することです ( を使用した初期化は、 で既に行っていることとよく似ています)。このように、 を呼び出すと、ダイアログでの操作が完了するまでメソッドの実行がブロックされるため、 を取得して で使用する前に、 が適切に初期化されていることを確認できます。createAndShowGUI()Password1JPanelJFramecreateAndShowGUI()FileOpener.actionPerformed()Password1keyFileOpener.actionPerformed()

最後にもう 1 つ: 注意してframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);ください ! メインウィンドウで使用しても問題ありませんが、セカンダリウィンドウで使用すると、プログラム全体が閉じるとすぐに完全にシャットダウンします. いずれにせよ、 のJDialogバージョンは有効な引数としてsetDefaultCloseOperation()受け入れられないため、メインウィンドウでのみ使用することになりますが、これで問題ありません。EXIT_ON_CLOSEFileOpener

于 2015-11-19T02:19:25.590 に答える