【问题标题】:Issue with password protected notepad in JavaJava中受密码保护的记事本问题
【发布时间】:2016-04-28 09:26:10
【问题描述】:

我无法理解为什么我的代码无法运行。

就目前而言,Eclipse 没有向我显示任何错误,但是当我尝试运行它时代码不会启动。

我的程序的想法是使用 JFrame 的受密码保护的记事本。

这是代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;

public class notepad extends JFrame implements ActionListener {
    public static void main(String args[]){}
    private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
    private MenuBar menuBar = new MenuBar();
    private Menu file = new Menu();
    private MenuItem openFile = new MenuItem(); 
    private MenuItem saveFile = new MenuItem();
    private MenuItem close = new MenuItem(); 
    public notepad() {
        this.setSize(700, 500); 
        this.setTitle("Projet Java"); 
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.textArea.setFont(new Font("Helvetica", Font.ROMAN_BASELINE, 12));
        this.getContentPane().setLayout(new BorderLayout()); 
        this.getContentPane().add(textArea);
        this.setMenuBar(this.menuBar);
        this.menuBar.add(this.file); 
        this.file.setLabel("File");
        this.openFile.setLabel("Open");
        this.openFile.addActionListener(this);
        this.file.add(this.openFile); 
        this.saveFile.setLabel("Save");
        this.saveFile.addActionListener(this);
        this.file.add(this.saveFile);
    }

    public void actionPerformed (ActionEvent e) {
        if (e.getSource() == this.close)
            this.dispose(); 
        else if (e.getSource() == this.openFile) {
            JFileChooser open = new JFileChooser(); 
            int option = open.showOpenDialog(this); 
            if (option == JFileChooser.APPROVE_OPTION) {
                this.textArea.setText(""); 
                try {
                    Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
                    while (scan.hasNext())
                        this.textArea.append(scan.nextLine() + "\n"); 
                } catch (Exception ex) { 
                    System.out.println(ex.getMessage());
                }
            }
        }
        else if (e.getSource() == this.saveFile) {
            JFileChooser save = new JFileChooser(); 
            int option = save.showSaveDialog(this); 
            if (option == JFileChooser.APPROVE_OPTION) {
                try {
                    BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
                    out.write(this.textArea.getText());
                    out.close(); 
                } catch (Exception ex) { 
                    System.out.println(ex.getMessage());
                }
            }
        }
    }
        static class password{ 
        public static String password = "password";

        public static void main(String args[]) {
                JFrame box = new JFrame("Password");
                box.setVisible(true);
                box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                box.setSize(400,100);

                JPasswordField pass = new JPasswordField(10);
                pass.setEchoChar('*');  
            }
                static class AL implements ActionListener{
                    public void actionPerformed(ActionEvent e){
                    JPasswordField input = (JPasswordField) e.getSource();
                    char[] pass = input.getPassword();
                    String yes = new String(pass);

                    if (yes.equals(password)){ 
                        notepad app = new notepad();
                        app.setVisible(true);
                    }else{
                        System.exit(0);
                    }


                    }
                }
        }
}

【问题讨论】:

  • pass 何时添加到任何内容中?
  • 您还有两个main 方法,所以我不知道您要调用哪个方法来开始工作。您还将重量级 (AWT) 组件与轻量级组件 (Swing) 混合在一起,这不会结束
  • @MadProgrammer 很好发现,我什至没有看到第一个 main 方法,它肯定没有做太多:public static void main(String args[]){}
  • 我不确定您需要什么,因为您只提到此代码不会运行。它会运行,它只是不做你期望它做的事情。您没有指定任何问题,所以我假设您希望它显示一个可以写入密码的字段。为此,您需要在声明 pass 后添加行 box.add(pass);
  • 我的问题是,如果没有第一个 main 方法,eclipse 找不到记事本类的 main。之前,我没有尝试为密码输入创建 GUI,当我使用扫描仪时它工作得很好。 @WrongRhyme 是的,很抱歉,我希望它首先运行密码字段,如果密码正确,则继续使用记事本。否则,我希望它关闭

标签: java swing jframe passwords notepad


【解决方案1】:
  • 您的第一个 main 方法是公开的,但为空,因此不会执行任何操作。
  • 您的第二个 main 方法位于非公共类中,因此 JVM 永远不会找到它来启动您的程序。
  • 您将 AWT 图形组件与 Swing 图形组件混合使用,规则是选择一种,切勿将两者混合使用。
  • 您的所有 Swing 应用程序都应在 SwingUtilities.invokeLater 内启动,以确保所有修改 GUI 的线程都由事件调度程序线程 (EDT) 执行。
  • 使用 JTextArea 时,请始终将其放在 JScrollPane 内,以便能够访问显示在组件大小之外的文本。

这是修改后的测试代码:

import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

@SuppressWarnings("serial")
public class Notepad extends JFrame
{
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    UIManager.setLookAndFeel(
                            "javax.swing.plaf.nimbus.NimbusLookAndFeel");
                }
                catch (ClassNotFoundException | InstantiationException
                        | IllegalAccessException
                        | UnsupportedLookAndFeelException e)
                {
                    e.printStackTrace();
                }
                new Notepad();
            }
        });
    }

    private JTextArea textArea = new JTextArea("", 0, 0);
    private JMenuBar menuBar = new JMenuBar();
    private JMenu file = new JMenu();
    private JMenuItem openFile = new JMenuItem();
    private JMenuItem saveFile = new JMenuItem();
    private JMenuItem close = new JMenuItem();
    private JFileChooser open, save;

    public Notepad()
    {
        setBounds(100, 100, 700, 500);
        setTitle("Projet Java");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        textArea.setFont(new Font("Helvetica", Font.ROMAN_BASELINE, 12));
        add(new JScrollPane(textArea));

        open = new JFileChooser();
        save = new JFileChooser();

        setJMenuBar(menuBar);
        menuBar.add(file);
        file.setText("File");

        openFile.setText("Open");
        openFile.addActionListener(e -> {
            if (open.showOpenDialog(
                    Notepad.this) == JFileChooser.APPROVE_OPTION)
            {
                textArea.setText("");
                try (BufferedReader br = new BufferedReader(
                        new FileReader(open.getSelectedFile())))
                {
                    String s = null;
                    while ((s = br.readLine()) != null)
                    {
                        textArea.append(s + "\n");
                    }
                }
                catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
        });
        file.add(openFile);

        saveFile.setText("Save");
        saveFile.addActionListener(e -> {
            if (save.showSaveDialog(
                    Notepad.this) == JFileChooser.APPROVE_OPTION)
            {
                try (BufferedWriter out = new BufferedWriter(
                        new FileWriter(save.getSelectedFile())))
                {
                    out.write(textArea.getText());
                }
                catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
        });
        file.add(saveFile);

        close.setText("Close");
        close.addActionListener(e -> {
            System.exit(0);
        });
        file.add(close);

        setVisible(true);
    }
}

【讨论】:

    【解决方案2】:

    原因可能是您的 public static void main(String args[]) 在内部(静态)类密码中,而不是在记事本类中。

    首先,我不知道您是不是精通Java 开发人员,但通常不鼓励使用小写字符命名类(类通常使用以下格式指定:MySuperCoolClass)。您也可以考虑不将其放在默认包中。

    我也会认真提醒您使用静态类,除非您绝对必须这样做,并认真建议您为每个窗口使用单独的类 - 使用完整的类。我还建议从启动器类创建主窗口并使用它来控制您的程序(最后一点只是我的个人经验——我不知道其他 Java 开发人员是否会这样做)。

    除此之外 - 您需要进入运行配置并选择 notepad$password 来执行。

    通过转到“运行”->“运行配置”菜单来执行此操作,然后在“主类:”字样下方的文本框中的主类中,有一个按钮 - 搜索 - 在窗口的最左侧,单击该按钮并选择记事本$密码。或者您可以输入“notepad$password”,它应该可以使用任何一种方式。

    您也可以从命令行尝试此操作 - cd 到 Eclipse 项目的 bin 目录并执行:

    java记事本$密码

    现在,如果我要提出一个建议,我建议您将以下代码(至少)添加到 main(String args[]) 方法 -

    public static void main(String args[]) {
                JFrame box = new JFrame("Password");
                box.setVisible(true);
                box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                box.setSize(400,100);
    
           JPasswordField pass = new JPasswordField(10);
                //add action listener 
                pass.addActionListener(new AL());
                //add the pass to the box 
                box.add(pass); ;  
            }
    

    您可能希望将 actionlistener 添加到密码框中,因为没有它您的程序将无法继续。当在框中按下回车键时,您的动作侦听器将触发。您还需要将您的通行证添加到框(您的 JFrame)中。

    使用上面的代码,并修改您的运行配置 - 这将运行,尽管它可能需要一些工作(例如,您可能希望在显示记事本后关闭密码对话框)。

    还有其他改进,例如将密码分离到自己的文件中,并创建一个启动器而不是从 GUI 中启动,但对于基本测试,这将让您工作。

    希望这会有所帮助:)

    阿列克谢

    【讨论】:

    • 谢谢,代码现在可以按我的意愿工作!是的,我对 Java 开发还很陌生,因此我的代码普遍草率。但这对我帮助很大。
    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2010-11-09
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多