我正在开发一个 UI java 应用程序,其组成为:
- 顶部标题
- 左侧菜单
- 标题文本
- 错误消息(显示在页面标题上)
- 中心容器(JPanel)根据所选菜单项(从左侧)进行动态更改
当出现任何计算错误时,错误消息会显示在应用程序的标题(页面标题中的位置)上。错误消息可以不同,错误消息由一行组成,但其他消息较长(2,3 行)
当出现长错误时,它可能会正确显示,也可能无法显示(该消息显示在其他组件之上)。 据我所知,在更改 UI 组件时,会独立调用 doLayout()、repaint() 方法,这些方法应该会纠正布局。
最近我读到了有关 EDT 的内容,并注意到应该根据 EDT 原则来组织 swing 应用程序。
我认为这将解决我的问题,因为所有操作都将同步,并且我将管理方法调用的连续性。
但现在,我没有足够的时间来重构应用程序,这计划在下一个版本中发布。
您知道另一种有助于调整布局的解决方案吗?这个问题非常棘手,我无法重现它。但它时不时就会出现。
非常感谢。 塞尔吉乌
PS:如果您有任何疑问或需要更多详细信息,请随时与我联系。
最佳答案
以下类检查 EDT 违规情况。在执行任何其他 GUI 相关代码之前安装它,如下所示:
RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
这是类(class):
import javax.swing.JComponent;
import javax.swing.RepaintManager;
import javax.swing.SwingUtilities;
public class CheckThreadViolationRepaintManager extends RepaintManager {
private boolean completeCheck = true;
public synchronized void addInvalidComponent(JComponent component) {
checkThreadViolations(component);
super.addInvalidComponent(component);
}
public boolean isCompleteCheck() {
return completeCheck;
}
public void setCompleteCheck(boolean completeCheck) {
this.completeCheck = completeCheck;
}
public void addDirtyRegion(JComponent component, int x, int y, int w, int h) {
checkThreadViolations(component);
super.addDirtyRegion(component, x, y, w, h);
}
private void checkThreadViolations(JComponent c) {
if (!SwingUtilities.isEventDispatchThread() && (completeCheck || c.isShowing())) {
Exception exception = new Exception("EDT Violation");
boolean repaint = false;
boolean fromSwing = false;
StackTraceElement[] stackTrace = exception.getStackTrace();
for (StackTraceElement st : stackTrace) {
if (repaint && st.getClassName().startsWith("javax.swing.")) {
fromSwing = true;
}
if ("repaint".equals(st.getMethodName())) {
repaint = true;
}
}
if (repaint && !fromSwing) {
//no problems here, since repaint() is thread safe
return;
}
exception.printStackTrace();
}
}
}
关于Java Swing : Paint(), doLayout() 未同步。例如。错误消息显示错误,在调整窗口大小时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4032559/