Java no response from other classes

人走茶凉 提交于 2019-12-08 11:50:22

问题


I have this GUI program where I'm trying to basically copy windows CMD. Since I have lots of features in this program, I decided to put parts of the code in different classes. But it doesn't respond.

       if(command.size()<2 && command.size()>0) {
            switch(command.get(0)) {
                case "dt":
                    getDateTime a = new getDateTime();
                    a.Start();
                    break;
                // other case(s) down below
            }
        }

Here is the geDateTime class

public class getDateTime {
    public static void Start() {
        Terminal t = new Terminal();
        try {
            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            Date date = new Date();
            String s = dateFormat.format(date).toString();
            t.print(s);
        }catch(Exception e){ e.printStackTrace(); }
    }
}

Here is the print(); void in the main class...

public static void print(String s) {
        Color c = Color.WHITE; // prints white text to JFrame
        Style style = output.addStyle("Style", null);
        StyleConstants.setForeground(style, c);
        try{
            document.insertString(document.getLength(), s, style);
        }catch(Exception e){e.printStackTrace();}
    }

Now when I enter the command for accessing the getDateTime class, the program freezes and I can't input anything. HOWEVER, if I just put the getDateTime class into a void inside the main class it works fine; but this would be a problem to just put everything into the main class since some function(s) could have hundreds of line of code.

No errors are produced when the program freezes.


回答1:


In the code snippet that you have earlier, the code was trying to create a new Terminal rather than using the existing one.

Try this:

private static void print() {
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date();
    String s = dateFormat.format(date).toString();
    print(s);
}

In the access method:

case "dt":
    print();
    break;

Update: On a side note, try to avoid static if at all possible. Generally speaking, it's bad practice. See https://stackoverflow.com/a/7026563/1216965



来源:https://stackoverflow.com/questions/22056226/java-no-response-from-other-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!