有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是框架。revalidate()在事件后获取输出是否重要?

因此,我编写了一个代码,在单击帧南部区域的按钮后,会得到一个矩形

但由于这个原因,在点击按钮后,代码似乎不起作用

public void actionPerformed(ActionEvent ev){
    Drawing d = new Drawing();
    frame.add(d);
    frame.repaint();
   }

以及在块内添加revalidate()

 public void actionPerformed(ActionEvent ev){
    Drawing d = new Drawing();
    frame.add(d);
    frame.revalidate();
    frame.repaint();
   }

现在代码运行得很好,但是从我研究的地方来看,他们没有使用revalidate(),他们的代码运行得很好

为什么会这样


共 (1) 个答案

  1. # 1 楼答案

    因此,您引用的示例是使用自定义绘制方法绘制组件。这不会(直接)影响组件的大小或位置,因此不需要容器来执行新的布局传递

    有关详细信息,请参见Performing Custom PaintingPainting in Swing

    您的代码正在向容器添加新组件,因此您需要告知容器何时需要重新布置容器

    所以,从JavaDocs

    public void revalidate()
    Supports deferred automatic layout. Calls invalidate and then adds this component's validateRoot to a list of components that need to be validated. Validation will occur after all currently pending events have been dispatched. In other words after this method is called, the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By default, JRootPane, JScrollPane, and JTextField return true from isValidateRoot.

    This method will automatically be called on this component when a property value changes such that size, location, or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke validate to get the contents of the GUI to update.