You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

if分支内JFrame尺寸设置异常:Cruise窗口受Cargo窗口影响

问题根源与修复方案

问题所在

你用compareToIgnoreCase(...) >= 0判断窗口标题的逻辑完全错误。字符串的compareToIgnoreCase方法返回的是两个字符串的字典序差值:

  • 当前字符串比目标字符串字典序大,返回正数
  • 字符串相等返回0
  • 当前字符串更小返回负数

当标题是"All Cruise ships"时,和"All Cargo ships"比较,"Cruise"字典序比"Cargo"大,compareToIgnoreCase会返回正数,满足>=0条件,导致代码直接进入Cargo船的分支,设置730x250的尺寸,根本不会走到Cruise船的分支。

修复代码

把判断条件改成严格相等的判断,使用equalsIgnoreCase方法:

else if (title.equalsIgnoreCase("All Cargo ships")){
    newFrame.setSize(730, 250);
    for(Ship for_cargo:dataFromFile){
        if(for_cargo instanceof Cargo)
        {
            Cargo cargo = (Cargo) for_cargo;
            text_to_be_set_in_specific_window += cargo.toString()+"\n";
            
        }
    }
}else if (title.equalsIgnoreCase("All Cruise ships")){
    newFrame.setSize(500, 250);
    for(Ship for_cruise: dataFromFile){
        if(for_cruise instanceof Cruise)
        {
            Cruise cruise = (Cruise) for_cruise;
            text_to_be_set_in_specific_window += cruise.toString()+"\n";
        }
    }           
}

补充说明

后续处理Yacht窗口时,同样用equalsIgnoreCase判断标题,确保每个分支只在标题完全匹配时触发,避免分支串扰。

内容的提问来源于stack exchange,提问作者Aagaman Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:07:44