简体   繁体   English

Java Jlabel-使用setText时不显示文本

[英]Java Jlabel - not displaying text when using setText

When modifying lblError I am using set text. 修改lblError时,我正在使用设置文本。 It is working in my try catch statements just fine. 它在我的try catch语句中正常工作。 But when I am running an else statement and it enters the else statement...(I have checked) the setText doesn't make the label display the text I want it to 但是当我运行else语句并输入else语句时...(我检查过),setText不会使标签显示我想要的文本

it works ehn this code is implemented: 该代码实现了,它可以工作:

try {
    Schedule newSched = ScheduleReader.read(text);
    for (int i = 0; i <= newSched.getLastFlightTime(); i++) {
        ArrayList<Flight> flightsAtTime = newSched.getFlights(i);

    for (Flight f : flightsAtTime) {
         s.add(f);
        }
    }
    flights= getArrayList(s);
    displaySchedule();
    lblError.setText("");

   } catch (IOException e1) {
    lblError.setText(IO_MESSAGE);
   } catch (FormatException e1) {
    lblError.setText(FORMAT_MESSAGE);
   } catch (DuplicateFlightException e1) {
    lblError.setText(DUPLICATE_FLIGHT_MESSAGE);
   }
}

but it doesn't work when I do: 但是当我这样做时不起作用:

 else{
        lblError.setText(FLIGHT_NOT_READY);
    }

Then either 1) the else statement is never called or 2) you're calling the method on a different JLabel object from the one displayed. 然后要么1)从不调用else语句,要么2)您正在与显示的JLabel对象不同的JLabel对象上调用该方法。

To test the first, do: 要测试第一个,请执行以下操作:

else{
   System.out.println("else block called");
   lblError.setText(FLIGHT_NOT_READY);
}

To test the second, check to make sure that you've not created a second instance of the class that holds the JLabel. 要测试第二个实例,请检查并确保没有创建包含JLabel的类的另一个实例。

Otherwise, if you're still stuck, consider giving us more information and code, as I don't think we have enough to be able to tell you with complete confidence what the cause of your problem is. 否则,如果您仍然遇到问题,请考虑向我们提供更多信息和代码,因为我认为我们没有足够的能力完全自信地告诉您问题的原因是什么。

You can't necessarily just call setText() on a visible label and have it take effect immediately -- especially if you're not calling it from an event handler. 您不必只在可见标签上调用setText()并使其立即生效- 特别是如果您不是从事件处理程序中调用它的话。 In general, if you change the appearance of a component that's showing on the screen, you must call validate() on the component to force the layout to be updated; 通常,如果您更改了屏幕上显示的组件的外观,则必须在组件上调用validate()以强制更新布局;否则,请执行以下操作。 in the case of an empty label getting new text, this is definitely going to be required. 如果空白标签获取新文本,则绝对需要这样做。

EDIT 编辑

And @HovercraftFullOfEels also has some good suggestions of other things that might be going wrong. @HovercraftFullOfEels也对其他可能出错的地方提出了一些好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM