Java GUI - How to append text to JTextArea from a static method? - java

I'm doing a simple exercise about client - server chat using Java IO. This is my code structure:
public class ChatRoomClientGUI{
private JTextArea textAreaMessages;
private JTextField textFieldMessage;
private JButton buttonSendMsg;
//...
private static Socket socket = null;
private static Scanner input = null;
private static PrintWriter output = null;
//...
private static void handleInputStream(){
String response = input.nextLine();
textAreaMessages.append(response + "\n"); // Error here
}
}
The problem I'm facing now is that I can't get access to the textAreaMessages variable because it is non-static and the handleInputStream() method is static. I've tried some ways but none of them works:
change textAreaMessages; to private static JTextArea textAreaMessages; => My IDE (IntelliJ IDEA) yield an error when I run the program
change handleInputStream() to a non-static method => This didn't work either because I call this method from a static context and this can't be changed.
So any ideas how to fix this problem ?
Thanks so much in advanced !

fairly ugly, but if you're sure there is going to be only one instance of your object, then modify (or add) the constructor to set a static variable to this:
private static ChatRoomClientGUI singleton;
...
public ChatRoomClientGUI() {
singleton = this;
...
}
private static void handleInputStream(){
String response = input.nextLine();
singleton.textAreaMessages.append(response + "\n");
}

You can create getter and setter for private JTextArea textAreaMessages; and while calling handleInputStream() pass the instance of this class and call the setter to append the text.
private static void handleInputStream(ChatRoomClientGUI gui) {
String response = input.nextLine();
gui.getTextField().append(response + "\n"); // Error here
}
public void setTextField(JTextField textField) {
this.textAreaMessages = textField;
}
public JTextField getTextField() {
return textAreaMessages;
}

Related

How to deal with "final fields may not have been initialized" issue with multiple static variables?

In this code, if I add 'final' to the variable definitions, I will receive "the final fields may have not been initialized" error. Some suggested solutions on Statckoverflow tend to be creating static functions to return the value. However, in this case I need to create four different functions to do that. Is there a more elegant solution to this issue?
private static String MODEL_PATH;
private static String VECTORS_PATH;
private static String NEG_PATH;
private static String POS_PATH;
static {
try {
MODEL_PATH = new ClassPathResource("models/word2vec_model").getFile().getAbsolutePath();
VECTORS_PATH = new ClassPathResource("models/model.zip").getFile().getAbsolutePath();
NEG_PATH = new ClassPathResource("models/neg.txt").getFile().getAbsolutePath();
POS_PATH = new ClassPathResource("models/pos.txt").getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
}
However, in this case I need to create four different functions to do that.
Since you are doing essentially the same thing, but with different resource names, one method would be sufficient:
private static String getResourceByName(string path) {
try {
return ClassPathResource(path).getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Now you can use the same method four times in your initialization:
private static final String MODEL_PATH = getResourceByName("models/word2vec_model");
private static final String VECTORS_PATH = getResourceByName("models/model.zip");
private static final String NEG_PATH = getResourceByName("models/neg.txt");
private static final String POS_PATH = getResourceByName("models/pos.txt");

String enum in Java

I have an enum:
public enum ListEnums {
TEST("test1"),
TEST2("test2");
private final String txt;
ListEnums(String str){
txt = str;
}
#Override
public String toString(){return txt;}
I want get the enum string without call .toString().
Like:mymethod(ListEnums.TEST);
No: mymethod(ListEnums.TEST.toString());
Is it possible?
EDIT
The string return must be contains special chars.
here:
public enum ListEnums {
TEST("test1"),
TEST2("test2);
private final String txt;
ListEnums(String str){
txt = str;
}
#Override
public String toString(){
return txt;
}
if you call ListEnum.TEST.name() you will get TEST which is almost the same as calling toString()... if you instead do ListEnum.TEST then the name will be printed...
so Renaming the Enum constants is the way to go...
and the best part is: you will get rid off the constructor, the toString method and the variable txt...
you just dont need it anymore. :)
It's OK, and a good practice to use getters in your enums. Also good to keep your constructor private (though enums are private by default)....
public enum ListEnums {
TEST("test1"),
TEST2("test2");
private final String txt;
private ListEnums(String str){
txt = str;
}
public String getTxt() {
return txt;
}
}
public static void main(String[] args) {
System.out.println(ListEnums.TEST.getTxt());
}

How can I create a generic setter for JTextField?

I am able to expose a private JTextField by doing this:
public void setTextField(String value) {
someTF.setText(value);
}
It would be a lot of work if I have a lot of JTextFields. I tried doing this but failed. No error it's just not setting the right value on specified JTextField.
public class SomeView {
private JTextField someTF = new JTextField(10);
...
public void initComponents() {
...
}
public void setTextField(JTextField jTF, String value) {
jTF.setText(value);
}
}
public class SomeViewTable implements ...{
public void mousePressed(MouseEvent e) {
if (e.getSource() == someButton) {
JTextField someTF = new JTextField(10);
String value = "Some Value";
SomeView sv = new SomeView();
sv.initComponents();
sv.setTextField(someTF, value);
}
}
}
Im expecting this to happen in SomeView class when I called method sameTextField
someTF.setText("Some Value");
Is this possible, what rules in java am I breaking here?
In your listener, you are creating a local variable:
JTextField someTF = new JTextField(10);
...
sv.setTextField(someTF, value);
But what you want is to set the text field of SomeView. So remove the first line, and replace the second with:
sv.setTextField(sv.someTF, value);
Now, to answer the more global question of how to expose many private JTextFields through one method, one possibility could be to assign a string ID to each of them, and store them all in a HashMap:
Map<String,JTextField> map = new HashMap<String,JTextField>();
map.put("field 1", textField1);
...
map.put("field n", textFieldn);
public void setTextField(String id, String value) {
map.get(id).setText(value);
}
Or you could simply generate getters automatically for all your fields (most IDE do that painlessly)...

How do i get the variable in a arraylist an set them to an label

In my first class i got a method that looks like this
public Private HentLogindOplysninger(String Brugernavn){
for(Private privat : privater){
if(privat.getAccountName().equals(Brugernavn)){
return privat;
}
}
return null;
}
an in my main class i created my object in the top like this
private static PrivateRegistre PR = new PrivateRegistre();
i call it
PR.HentLogindOplysninger(KundeId);
but how do I get private and separates it, and put the different variable in each label?
Is it this you want?
final Private myPrivate = PR.HentLogindOplysninger(KundeId);

java - an enum question

I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx

Categories