gpt4 book ai didi

Java 对象方法不可访问

转载 作者:行者123 更新时间:2023-11-30 06:11:54 25 4
gpt4 key购买 nike

在下面的代码中,如果我调用 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();
}
}

最佳答案

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

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('%');
//...

关于Java 对象方法不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com