2013-10-12 56 views
0

我想要做的就是加載保存在純文本文件中關於JInternalFrame位置的信息,並將該幀設置爲保存爲的狀態。出於某種原因,我無法將捕獲組與字符串進行比較;也就是matcher.group("state")與它應該是的字符串("min","max""normal")相比並不是真的,並且matcher.group("vis")也是如此。java.util.regex.Matcher.group和字符串比較之間的不連續性

String fileArrayStr = "WINDOW_LAYOUT:0,0|779x768|max|show" 

我的代碼是:

byte[] fileArray = null; 
String fileArrayStr = null; 
try { 
    fileArray = Files.readAllBytes(PathToConfig); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
try { 
    fileArrayStr = new String(fileArray, "UTF-8"); 
} catch (UnsupportedEncodingException e) { 
    e.printStackTrace(); 
} 

// checking the value of fileArrayStr here by outputting it 
// confirms the data is read correctly from the file 

pattern = Pattern.compile(
    "WINDOW_LAYOUT:\\s*" + 
    "(?<x>[0-9\\-]+),(?<y>[0-9\\-]+)\\|" + 
    "(?<length>\\d+)x(?<height>\\d+)\\|" + 
    "(?<state>[minaxorl]+)\\|" + 
    "(?<vis>[showide]+)\\s*"); 
matcher = pattern.matcher(fileArrayStr); 
if (matcher.find()) { 
    frame.setLocation(Integer.parseInt(matcher.group("x")), 
        Integer.parseInt(matcher.group("y"))); 
    frame.setSize(Integer.parseInt(matcher.group("length")), 
        Integer.parseInt(matcher.group("height"))); 
    DialogMsg("state: " + matcher.group("state") + "\n" + "vis: " 
        + matcher.group("vis")); 

    // the above DialogMsg call (my own function to show a popup dialog) 
    // shows the 
    // data is being read correctly, as the values are "max" and "show" 
    // for state 
    // and vis, respectively. Same with the DialogMsg calls below. 

    if (matcher.group("state") == "min") { 
     try { 
      frame.setIcon(true); 
     } catch (PropertyVetoException e) { 
      e.printStackTrace(); 
     } 
    } else if (matcher.group("state") == "max") { 
     try { 
      frame.setMaximum(true); 
     } catch (PropertyVetoException e) { 
      e.printStackTrace(); 
     } 
    } else { 
     DialogMsg("matcher.group(\"state\") = \"" 
         + matcher.group("state") + "\""); 
    } 
    if (matcher.group("vis") == "show") { 
     frame.setVisible(true); 
    } else if (matcher.group("vis") == "hide") { 
     frame.setVisible(false); 
    } else { 
     DialogMsg("matcher.group(\"vis\") = \"" + matcher.group("vis") 
         + "\""); 
    } 
} 

的代碼總是回落至else語句。我究竟做錯了什麼? matcher.group應該返回一個字符串,不是嗎?

+0

請格式化您的代碼。 –

+0

我不知道你的意思是通過格式化我的代碼。它已經格式化。絕對不是重複的。僅僅因爲兩個問題可能具有相同的答案並不意味着問題本身就是重複的...... – stoicfury

+2

當它全部在一行上時很難閱讀代碼。格式化它以便一條語句= 1行。你不知道如何比較字符串值,這就是爲什麼你的代碼不會像你期望的那樣。這是重複的,你不知道它。 –

回答

1

變化

if(matcher.group("state") == "min") 

if(matcher.group("state").equals("min")) 

不要使用==比較Strings。您應該使用.equals.equalsIgnoresCase方法。

2

您正在比較字符串的「==」運算符,它將比較對象,以便條件變爲false,並將其轉到代碼的else部分。因此,代替「==」運算符嘗試使用.equals或.equalsIgnoresCase方法。