repaint() Method in Java

大憨熊 提交于 2019-12-04 08:18:01

The repaint() refreshes the view (component), so whenever you make any change on the component, you must call it. For instance, if you rotate the graphical component, you must make a call to repaint() in order to see the change on the containing component

It's never really necessary in most swing applications, because they handle it automatically (for common operations such as changing text values on buttons and adding data to a list box).

Generally, it's only if you've made some sort of change that swing won't automatically pick up - for example, you're not using a layout manager and are resizing components manually (because normally the layout manager repaints its components when necessary).

When you launch your application, you "paint" your GUI.

You need to call repaint() when you want to re-draw your GUI because you have changed something inside.

If you want to delete a button, you need to remove it (or make it invisible) then you need to call validate() or repaint() to re-calculate (re-draw) the GUI.

The only stuff I can think of:

    new Thread() {
    @Override
    public void run() {
    while (ClassName.this.isVisible()) {
        ClassName.this.updateStatusLabel();
        ClassName.this.validate();
        ClassName.this.repaint(50L);
        try {
        Thread.sleep(1000);
        } catch (final InterruptedException e) {
        Log.log(e);
        }
    }
    }
}.start();

Suppose you have the above code in the constructor of a JDialog. What updateStatusLabel does is checking a boolean variable, either public or settable through a method, and set the icon of a JLabel in base to such boolean. If you don't validate and repaint the GUI, the modification won't be shown until another event, most likely an user-triggered one, is thrown. And, if the user is waiting for the label to show a certain icon because of, let's say, it indicated if a device is reachable through the Internet, he/she'll never interact (or, at least, you're delaying interactions so much).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!