how to update a textbox from a static class?
This is driving me nuts. I have a working text based application. It has many many variables which now need a GUI. I'm starting with the basics. Whenever some data is sent to my log, I want it to display in my textbox.
Here is a unified entry point for data to pass where it can be manipulated.
public class Log {
private static void consoleOut(String data) {
System.out.println(data);
OBD2nerConsole.update(data);
}
public static void level0(String data) {
if (Status.ConsoleLevel >= 0) {
consoleOut(data);
}
This is my form and it has a text box and a few buttons.
public class OBD2nerConsole extends java.awt.Frame {
public static void update(String data) {
textField1.setText(textField1.getText() + data);
}
开发者_开发技巧
}
The prolem I am having is that I am working with a static and non-static I guess.. There is nothing displayed in the text box. I kept playing around and removed all of the errors but it is not working. I don't really know what to do. It seems that this is the best configuration, because there are no errors, but the text box is not doing anything.
I should probly add that this is my first form EVER!
Assuming that textField1
is an attribute of the parent class, the update
method should not be static
. That of course means that you need to apply the method to an instance of the ODB2tunerConsole
object.
The rule in Java is that a static
method cannot access the non-static attributes and methods of its class with explicitly using a reference to an instance of the class.
This leads people who are new to object-oriented programming in Java to try to make everything static. But as you see, that leads to trouble. The correct solution is to limit your use of statics to cases where they are really needed. These are as follows:
- Shared constants; e.g.
public static final String FOO = "foo";
- Helper methods that depend only on the state of their arguments.
- Hidden references to global data structures, exposed (if necessary) using the "singleton" pattern.
If you give Log a static reference to an instance of OBD2nerConsole and remove static from update(String) you should be able to update the textField1.
Listing of modified Log.java
:
public class Log {
private static Updatable console = Updatables.getUpdatable();
private static void consoleOut(String data) {
System.out.println(data);
console.update(data);
}
public static void level0(String data) {
if (Status.ConsoleLevel >= 0) {
consoleOut(data);
}
}
}
Listing of Updatable.java
:
public interface Updatable {
void update(String);
}
Listing of modified snippet of ODB2nerConsole.java
:
public class OBD2nerConsole extends java.awt.Frame implements Updatable {
@Override
public void update(String data) {
textField1.setText(textField1.getText() + data);
}
}
Listing of Updatables.java
:
public class Updatables {
public Updatable getUpdatable() {
return new ODB2nerConsole();
}
}
精彩评论