2

在下面的代码中,如果我调用 password.setEchoCar( char ) 方法,文件运行良好。为什么当对象在它上面创建时我不能调用它?

不应该有范围问题,我检查了 javadoc 的方法,这似乎是指定非默认密码字符的正确方法。

谢谢

import javax.swing.*;

public class Authenticator extends javax.swing.JFrame {

    JTextField username = new JTextField(15);
    JPasswordField password = new JPasswordField(15);
    password.setEchoChar('%');
    JTextArea comments = new JTextArea(4, 15);
    JButton ok = new JButton("OK");
    JButton cancel = new JButton("Cancel");

    public Authenticator () {
        super("Account Information");
        setSize(300, 220);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel pane = new JPanel();
        JLabel usernameLabel= new JLabel("Username: ");
        JLabel passwordLabel = new JLabel("Password: ");
        JLabel commentsLabel = new JLabel("Comments: ");
        comments.setLineWrap(true);
        comments.setWrapStyleWord(true);
        pane.add(usernameLabel);
        pane.add(username);
        pane.add(passwordLabel);
        pane.add(password);
        pane.add(commentsLabel);
        pane.add(comments);
        pane.add(ok);
        pane.add(cancel);
        add(pane);
        setVisible(true);
    }

    private static void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }

    public static void main(String[] arguments) {
        Authenticator.setLookAndFeel();
        Authenticator auth = new Authenticator();
    }
}
4

2 回答 2

5

您正在尝试在可执行上下文之外(在变量声明区域内)执行代码......

public class Authenticator extends javax.swing.JFrame {

    JTextField username = new JTextField(15);
    JPasswordField password = new JPasswordField(15);
    password.setEchoChar('%');
    //...

    public Authenticator () {
        //...

移动password.setEchoChar('%');到构造函数

public class Authenticator extends javax.swing.JFrame {

    JTextField username = new JTextField(15);
    JPasswordField password = new JPasswordField(15);
    //...

    public Authenticator () {
        super("Account Information");
        password.setEchoChar('%');
        //...
于 2015-11-05T03:35:01.683 回答
0
JPasswordField password = new JPasswordField(15);
{
  password.setEchoChar('%');
}

您可以在初始化程序块中执行此操作,但除非您具有许多构造函数通用的初始化代码,否则在构造函数中执行此操作被认为是一种很好的风格。

于 2015-11-05T03:39:51.473 回答