HTTP Problem mit static/non static JTextArea Update

  • Themenstarter Themenstarter xInvictus
  • Beginndatum Beginndatum
X

xInvictus

Gast
Guten Tag,

ich bin gerade dabei, ein kleines Chat/Shoutbox Applet zu schreiben, welche alle 5 sekunden mit einer PHP-Datei auf dem Server kommuniziert, welche das Protokoll als HTML formatiert zurücklierfert, dieser neue Inhalt der JTextArea soll nun den bisherigen ersetzen, das ist die Logik.

Praktisch estellt sich das folgende Problem: Meine Main-Methode ist STATIC, in der die Routine läuft:
Java:
public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
        for(;;) {
    		try {
    			URL url = new URL("chat.php");
    			PhpPostConnect con = new PhpPostConnect(url);
    			try {
    			 con.send("sets=show");
    			 textArea.setText(con.read());
    			} catch (IOException e) {
    			e.printStackTrace();
    			}
    			} catch (MalformedURLException e) {
    			e.printStackTrace();
    			}
    			try {
    				Thread.sleep(5000);
    				} catch (InterruptedException e){
    				 // ERROR
    				}

    	}
    }
Mein Eclipse gibt mir hier den Fehler aus "Cannot make a static reference to the non-static field textArea"...

Hier noch einmal der Code im Ganzen, für besseres Verständnis von Klassen/Methoden und Variabel zusammenhängen:
Java:
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;


public class Test extends JPanel implements ActionListener {
    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";

    public Test() {
        super(new GridBagLayout());

        textField = new JTextField(80);
        textField.addActionListener(this);

        textArea = new JTextArea(40, 80);
        textArea.setEditable(false);
        textArea.setText("Loading...");
        JScrollPane scrollPane = new JScrollPane(textArea);

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
    }

    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();

        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("DontEvenTrip Chat Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new Test());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
        for(;;) {
    		try {
    			URL url = new URL("chat.php");
    			PhpPostConnect con = new PhpPostConnect(url);
    			try {
    			 con.send("sets=show");
    			 textArea.setText(con.read());
    			} catch (IOException e) {
    			e.printStackTrace();
    			}
    			} catch (MalformedURLException e) {
    			e.printStackTrace();
    			}
    			try {
    				Thread.sleep(5000);
    				} catch (InterruptedException e){
    				 // ERROR
    				}

    	}
    }
}

Vielen Dank im Vorraus!
 
TextArea ist nicht statisch, d.h. man kann das nicht in einer statischen Methode verwenden. Du musst entweder die TextArea statisch machen oder eine nicht statische Methode implementieren und diese von der Main aufrufen lassen.
 
wenn ich die TextArea also statisch initialisiere
Java:
protected static JTextArea textArea;

bekomme ich dieses

Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:86)
 
Welche Zeile ist das?

Ich nehme an, dass es daran liegt, dass textArea null ist.

Wenn du dein Programm startest, dann wird nur die statische main() ausgeführt. D.h. es wird nicht ein Test-Objekt erstellt und entsprechend auch nicht der Konstruktor aufgerufen. Normalerweise solltest du die Main-Methode in eine Start-Klasse auslagern ...
 
Zuletzt bearbeitet:
deine for schleife läuft noch an, bevor du die textarea erstellt hast. deswegen kommt die npe.

ich würde dir empfehlen die for schleife aus der main zu nehmen und als extra thread in der klasse Test zu starten. dann hast du auch keine probleme mehr mit dem non-static.
 
Dürfte ich fragen wo genau? und vor allem wie ich das genau in den Thread packe?

dies ist das Routine-Fragment

Java:
for(;;) {
    		try {
    			URL url = new URL("chat.php");
    			PhpPostConnect con = new PhpPostConnect(url);
    			try {
    			 con.send("sets=show");
    			  textArea.setText(con.read());
    			} catch (IOException e) {
    			e.printStackTrace();
    			}
    			} catch (MalformedURLException e) {
    			e.printStackTrace();
    			}
    			try {
    				Thread.sleep(5000);
    				} catch (InterruptedException e){
    				 // ERROR
    				}

    	}

Und dies der Gesamtcode, (noch einmal, da ich soeben die write-methode realisiert habe)

Java:
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;


public class Test extends JPanel implements ActionListener {
    protected JTextField textField;
    protected JTextArea textArea;
    public static String ign;
    private final static String newline = "\n";
    
    for(;;) {
		try {
			URL url = new URL("http://det.jet-development.net/chat.php");
			PhpPostConnect con = new PhpPostConnect(url);
			try {
			 con.send("sets=show");
			  textArea.setText(con.read());
			} catch (IOException e) {
			e.printStackTrace();
			}
			} catch (MalformedURLException e) {
			e.printStackTrace();
			}
			try {
				Thread.sleep(5000);
				} catch (InterruptedException e){
				 // ERROR
				}

	}

    public Test() {
        super(new GridBagLayout());

        textField = new JTextField(80);
        textField.addActionListener(this);

        textArea = new JTextArea(40, 80);
        textArea.setEditable(false);
        textArea.setText("Loading...");
        JScrollPane scrollPane = new JScrollPane(textArea);

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
    }

    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        try {
			URL url1 = new URL("http://det.jet-development.net/chat.php");
			PhpPostConnect con1 = new PhpPostConnect(url1);
			try {
			 con1.send("sets=write&name=" + ign + "&text=" + text);
			 textArea.setText(con1.read());
			} catch (IOException e) {
			e.printStackTrace();
			}
			} catch (MalformedURLException e) {
			e.printStackTrace();
			}
        
       // textArea.append(text + newline);
       // textField.selectAll();

        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
    	String response = JOptionPane.showInputDialog(null,
    			  "What is your name?",
    			  "Enter your name",
    			  JOptionPane.QUESTION_MESSAGE);
    	ign = response;
        JFrame frame = new JFrame("DontEvenTrip Chat Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new Test());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
 
Upps, entschuldigung für den doppelpost

//edit, ich habe vorhin den URL verkürzt auf die Datei, hier steht nun der Eigentliche im 2. Code des letzten Beitrages... Als Gast kann ich leider nichts verändern
 
Ich muss dazu sagen, dass ich normalerweise Threads mit "extends Thread" erzeuge, jedoch besitzt Test bereits eine Vererbung, somit bin ich momentan etwas überfordert .s wäre nett, wenn sich jemand die Zeit nehmen würde und die beiden Teile wir besagt mit einem Thread zusammenfügen könnte... Danke für die schnelle Hilfe und im Vorraus!
 
du nimmst statt
Code:
extends Thread
einfach
Code:
implements Runnable
.
Danach kannst du mit
Code:
new Thread(this);
einen neuen Thread erzeugen, der deine implementierte run() methode verwendet.
 
Ah, okay, danke.

Nun deklariere ich meine Class wie folgt
Java:
public class Test extends JPanel implements ActionListener, Runnable

und beginne die Klasse so;
Java:
protected JTextField textField;
    protected JTextArea textArea;
    public static String ign;
    private final static String newline = "\n";
    
    Thread t1 = new Thread(this);
    
    
    public void run() {

        while(true) {    
        	try {
    			URL url = new URL("http://det.jet-development.net/chat.php");
    			PhpPostConnect con = new PhpPostConnect(url);
    			try {
    			 con.send("sets=show");
    			  textArea.setText(con.read());
    			} catch (IOException e) {
    			e.printStackTrace();
    			}
    			} catch (MalformedURLException e) {
    			e.printStackTrace();
    			}
    			try {
    				Thread.sleep(5000);
    				} catch (InterruptedException e){
    				 // ERROR
    				}
        }
      }
Nun... er spuckt keine Fehler mehr aus... Allerdings auch kein Chatprotokoll :s
 
weil du den Thread noch starten musst. :rtfm:

irgendwo (z.b. im Kontruktor nachdem alle Komponenten erstellt wurden) musst du dann noch
Code:
t1.start();
schreiben.
 
/facepalm, der einfachste Fehler xD

Jedenfalls denke ich ist hier ein geeigneter Ort:

Java:
private static void createAndShowGUI() {
    	String response = JOptionPane.showInputDialog(null,
    			  "What is your name?",
    			  "Enter your name",
    			  JOptionPane.QUESTION_MESSAGE);
    	ign = response;
        JFrame frame = new JFrame("DontEvenTrip Chat Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new Test());

        frame.pack();
        frame.setVisible(true);
        t1.start(); // <--- HIER!
    }
Doch... drei mal dürft ihr raten, was der Fehler ist... RICHTIG! Unser lieber Freund static meldet sich zu Diensten...
 
Ja, mir ist bewusst, das das nicht der Konstruktor ist, würde ich es jedoch unter den Funktionsaufruf schreiben käme das Selbe problem, da main natürlich static ist...
 
aus der createAndShowGUI() und der main() kannst du den Thread natürlich nicht starten.

Du solltest dich vllt nochmal in die Grundlagen einlesen und danach nochmal deine komplette Struktur überdenken. Da hakts an mehreren Stellen.

Jetzt nochmal zum Thread:
Irgendwie kommts mir vor dass du die main für den Konstruktor hälst. Hier mal nen kleines Beispiel:

Java:
public class Test implements Runnable {
    Thread t1 = null;

    public Test() {
        t1 = new Thread(this);
        t1.start();
    }

    public void run() {
         /* do something */
    }
}
 

Zurück
Oben