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 に答える