[英]Java setText() Error
我不明白為什么在嘗試將.setText()到程序中的JTextArea對象時出現運行時錯誤。 在我的主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約定。 變量以小寫字母開頭。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.