Java setText() 错误

标签 java swing

我不明白为什么当我尝试在程序中对 JTextArea 对象进行 .setText() 时会出现运行时错误。在我的主 GUI 类中,我设置了一个创建弹出 JFrame 对象的事件,该 JFrame 中有一个按钮,也设置了 JTextArea.setText();到我的主 GUI 类中名为 MainOut 的 JTextArea。

public class GUI extends JFrame implements ActionListener {



JTextArea MainOut       =       new JTextArea(20,50);


public void actionPerformed(ActionEvent e) {


        if (e.getSource() == ExitVar){
            System.exit(0);
        }

        else if (e.getSource() == ServerLoginVar) { //This is my event that creates a 
                                                            //new JFrame popup
            new ServerLoginGUI(this);   
        } 

//-------------------------------------------------------------------
public class ServerLoginGUI extends JFrame implements ActionListener {

    JTextField ServerIP             = new JTextField(15);
    JPasswordField ServerPassword       = new JPasswordField(15);
    JPanel ServerLoginPanel         = new JPanel();
    JButton LoginButton         = new JButton("Login");
    JTextArea Area;
    JLabel ServerIPLabel            = new JLabel("Server Address:");
    JLabel ServerPasswordLabel      = new JLabel("Password      :");
    GUI GUi;
   public void actionPerformed(ActionEvent e) {

        if (e.getSource() == LoginButton){
            if (ServerIP.getText().isEmpty() ||  ServerPassword.getText().isEmpty()){
                } //do nothing

            else {
                new ServerAccess(this);

// this is the .setText() that will generate a error

                GUi.SiteNameField.setText("Test from the ServerLogin event!");

                dispose();}
                    }
        }

}

最佳答案

好吧,这就是你的问题。您已在ServerLoginGUI 类中创建了GUI 对象。但是您没有使用调用类的引用来初始化您的 GUI 对象。以下是您需要执行的操作来解决此问题。向您的 ServerLoginGUI 类添加以下构造函数:

public ServerLoginGUI(GUI gui)
{
  this.GUi = gui;
}

现在您的代码应该可以正常工作并且不会出现运行时错误。尽管您没有指定,但我假设这是一个空指针错误。

PS:请正确理解 Java 约定。变量以小写字母开头。 :)

关于Java setText() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630484/

相关文章:

Java线程队列重叠

java - 如何在Java中逐行传递args?

java - 如何表示垂直的 showOptionDialog 按钮

java - 当 Button 获得焦点时更改图标

java - 无法使用 Runtime.Exec 传递远程命令 (ssh)

java - 使用证书 .cer 连接到 Java 项目中的 Web 服务

Java转换整数到字符串不一致

java - 使用 KeyListener JAVA 的计算器

java - 已读和未读图书申请

Java - 使用 Netbeans 隐藏/显示外部 jPanel?