Модераторы: LSD, AntonSaburov

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Обьясните пожалуйста что такое invokeLater() ? 
:(
    Опции темы
604
Дата 27.4.2005, 14:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 56
Регистрация: 15.4.2005

Репутация: 1
Всего: 1



Обьясните пожалуйста что такое SwingUtilities.invokeLater() как его использовать и для чего это нужно?
PM MAIL   Вверх
batigoal
Дата 27.4.2005, 14:39 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Цитата
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
Runnable doHelloWorld = new Runnable() {
    public void run() {
        System.out.println("Hello World on " + Thread.currentThread());
    }
};

SwingUtilities.invokeLater(doHelloWorld);
System.out.println("This might well be displayed before the other message.");
If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed. Note that if the doRun.run() throws an uncaught exception the event dispatching thread will unwind (not the current thread).
Additional documentation and examples for this method can be found in How to Use Threads, in The Java Tutorial

Добавлено @ 14:41
Цитата
You can call invokeLater from any thread to request the event-dispatching thread to run certain code. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater. The invokeLater method returns immediately, without waiting for the event-dispatching thread to execute the code. Here's an example of using invokeLater:

Runnable updateAComponent = new Runnable() {
    public void run() { component.doSomething(); }
};
SwingUtilities.invokeLater(updateAComponent);


Хотя вот мне это все ничего не объяснило. Подождем кого-нибудь умного... smile
Добавлено @ 14:43
Видимо, запускает код немедленно, не дожидаясь, пока отработает код обработки событий, находящихся в очереди. Пример, когда это может понадобиться, придумать не могу.


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
604
Дата 27.4.2005, 14:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 56
Регистрация: 15.4.2005

Репутация: 1
Всего: 1



Код

Runnable doHelloWorld = new Runnable() {
    public void run() {
        System.out.println("Hello World on " + Thread.currentThread());
    }
};
SwingUtilities.invokeLater(doHelloWorld);
System.out.println("This might well be displayed before the other message.");

У меня выдает:
Hello World on Thread[AWT-EventQueue-0,6,main]
This might well be displayed before the other message.
А должно быть наоборот?

Это сообщение отредактировал(а) 604 - 27.4.2005, 14:51
PM MAIL   Вверх
batigoal
Дата 27.4.2005, 15:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Посмотри, какой странный результат я получил при выполнении такого кода:

Код

import javax.swing.*;

public class Form extends JPanel
{
    public static void main(String[] args)
    {
        final JFrame frame = new JFrame("Form");
        final MyPanel f = new MyPanel();
        frame.setContentPane(f);
        frame.setSize(200, 200);

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.show();

        Runnable doHelloWorld = new Runnable() {
            public void run() {
                System.out.println("Hello World on " + Thread.currentThread());
            }
        };
        for(int i =0; i<100; i++ )
        {
        SwingUtilities.invokeLater(doHelloWorld);
        System.out.println("This might well be displayed before the other message.");
        System.out.println();
        }
    }
}


Результат привожу полностью:

Цитата
This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
This might well be displayed before the other message.
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

This might well be displayed before the other message.

Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]
Hello World on Thread[AWT-EventQueue-0,6,main]


ох уж мне эта многопоточность...


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
AntonSaburov
Дата 27.4.2005, 15:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Штурман
****


Профиль
Группа: Модератор
Сообщений: 5658
Регистрация: 2.7.2002
Где: Санкт-Петербург

Репутация: 10
Всего: 118



Это в принципе идея того же треда, но более изощренная. В общем виде - твой обработчик будет поставлен в очередь событий для AWT и будет обработан уже после очередных задач.

В твоем случае событий там само собой нет, поэтому выполняем практически сразу.
PM MAIL WWW ICQ   Вверх
batigoal
Дата 27.4.2005, 15:43 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Если заменить
Код

SwingUtilities.invokeLater(doHelloWorld);

на обычный
Код

doHelloWorld.run();

то получим
Цитата
Hello World on Thread[main,5,main]
This might well be displayed before the other message.

Hello World on Thread[main,5,main]
This might well be displayed before the other message.

Hello World on Thread[main,5,main]
This might well be displayed before the other message.

................................


Логично.

Но применения этой возможности я вске равно не вижу. Разве что, как там написано, изменение GUI.


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
AntonSaburov
Дата 27.4.2005, 15:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Штурман
****


Профиль
Группа: Модератор
Сообщений: 5658
Регистрация: 2.7.2002
Где: Санкт-Петербург

Репутация: 10
Всего: 118



Цитата(Lamer @ 27.4.2005, 15:43)
Разве что, как там написано, изменение GUI.

Именно для этого и используется. Например ты хочешь изменить какие-то картинки на форме, но делать это прямо в обработчике например для кнопки - дело не очень мудрое. Графика и так в отдельном треде - потому результат может быть совсем странный. А так ты уверен, что твои изменения будут вызваны в нужное время. И самое главное это не завесит обработчик - ты из invokeLater выходишь сразу.
PM MAIL WWW ICQ   Вверх
batigoal
Дата 27.4.2005, 15:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Спасибо. Теперь нам с 604 все понятно. smile


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
Guest
Дата 27.4.2005, 16:41 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Lamer George
УУпс пока еще не совсем понятно smile
Можно еще пример, совсем на пальцах если незатруднит, или от вас
AntonSaburov
  Вверх
batigoal
Дата 27.4.2005, 16:59 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Ну если на пальцах, то так:

Помимо основного потока программы (понятие потока расшифровывать не надо?), в ней существуют еще некоторые, "неявные" потоки, в частности, поток-диспетчер событий. Назначение его состоит в том, чтобы обрабатывать события интерфейса. Если мы будем клацать по интерфейсу слишком быстро (1000 кликов по кнопке в секунду smile ), то у нас образуется очередь событий, которая будет постепенно обрабатываться. Применительно к данной ситуации, если мы будем еще параллельно выполнять какие-то вычисления, то у нас будет обычное параллельное выполнение, как в моем примере 2.
Теперь допустим, что у нас есть ситуация, когда нам необходимо перестроить интерфейс во время выполнения программы. Тогда это лучше сделать не немедленно, а тогда, когда мы обработаем всю скопившуюся у нас на входе очередь событий. Тогда мы используем invokeLater() и наш поток выполнится лишь тогда, когда очередь очистится (пример 1).


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
Stampede
Дата 27.4.2005, 20:24 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Гносеолог
**


Профиль
Группа: Участник Клуба
Сообщений: 963
Регистрация: 25.4.2005
Где: Calgary, Alberta, Canada

Репутация: 1
Всего: 144



Цитата(604 @ 27.4.2005, 14:35)
Обьясните пожалуйста что такое SwingUtilities.invokeLater() как его использовать и для чего это нужно?


Объясняю. Так уж устроен AWT, что все оконные события выстраиваются в одну очередь и обрабатываются по порядку. Пока событие полностью не обработано, никаких видимых результатов на экране не будет.

В большинстве случаев обработка тривиальная, все происходит быстро и никаких тормозов не заметно. Но иногда нажатие кнопки или еще какое-нибудь пользовательское действие запускает операцию, которая занимает ощутимое время: типа мощное вычисление, установка соединения или чтение/запись большого файла. Допустим, это длится одну минуту. Если ничего специально не предпринимать, юзер будет целую минуту тупо сидеть перед застывшим экраном и вообще не иметь ни малейшего понятия, что происходит. При этом вы в коде обработчика можете ему там выводить всякие надписи, показывать индикатор прогресса и т. д. - все псу под хвост, потому как отобразится это дело только когда вы вернете управление потоку, а это произойдет не раньше, чем ваша долгая операция так или иначе завершится.

Выход тут в том, чтобы создавать для таких долгих штук отдельный поток и там их выполнять, а управление главному потоку обработки событий возвращать немедленно. Теперь вроде все нормально, но вы хотите, допустим, по мере продвижения операции выводить сообщения о прогрессе. Так вот, если это делать напрямую, типа там JTextArea.append("Еще один демульгатор был эксторнизирован\n"), то это чревато неприятностями, потому как многие классы в AWT/Swing не являются thread-safe (ну если вам так уж не нравятся оригинальные английские термины, пускай будут потокобезопасными smile ).

Чтобы обновления такого рода были потокобезопасными, рекомендуется делать их потокобезопасным образом: заворачивать в объект типа Runnabe и подсовавать диспетчеру событий через посредство SwingUtilities.invokeLater(). Тогда, если в данный момент никакие кнопочки не нажимаются и ничего не происходит, обновление сразу и перерисуется, а если что-то уже обрабатывается, ваш запрос на обновление будет поставлен в очередь и получит возможность выполниться, когда до него дойдет очередь.

Вот зачем, собственно, нужен invokeLater().



--------------------
"If you want something done right, do it yourself"
По секрету: выучить английский - реально!
PM WWW   Вверх
batigoal
Дата 27.4.2005, 20:55 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 7
Всего: 151



Цитата(Stampede @ 27.4.2005, 20:24)
ну если вам так уж не нравятся оригинальные английские термины, пускай будут потокобезопасными 

Не всем, только мне. smile

Спасибо.



--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
604
Дата 28.4.2005, 10:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 56
Регистрация: 15.4.2005

Репутация: 1
Всего: 1



Всем спасибо! Написали очень понятно! Прошу прошения, но снова понял не до конца smile
Написал небольную программку, и не могу понять в чем тут проблема если я не использую этот invokeLater, и где конкретно в этом случае надо применять invokeLater?
Код

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test
{
  public Test()
  {
    JFrame frame = new JFrame();
    JButton button = new JButton("Push");
    final JLabel label = new JLabel("Status");

    button.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        Thread t = new Thread()
        {
          public void run()
          {
            try
            {
              for (int i = 0; i < 99; i++)
              {
                label.setText("Load: " + i + "%");
                sleep(100);
              }
            }
            catch (Exception e)
            {}
          }
        };
        t.start();
      }
      });
    frame.getContentPane().add(button, BorderLayout.CENTER);
    frame.getContentPane().add(label, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 160);
    frame.setVisible(true);
  }

  public static void main(String[] args)
  {
    new Test();
  }
}

Вроде понимаю что такое очередь и что что такое поток, но вот где применять и для какого случая этот invokeLater не понимаю smile Хелп!
PM MAIL   Вверх
Stampede
Дата 28.4.2005, 11:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Гносеолог
**


Профиль
Группа: Участник Клуба
Сообщений: 963
Регистрация: 25.4.2005
Где: Calgary, Alberta, Canada

Репутация: 1
Всего: 144



Цитата(604 @ 28.4.2005, 10:54)
не могу понять в чем тут проблема если я не использую этот invokeLater


Код не проверял, но выглядит вполне работающим. Проблема может быть в следующем. Вот у тебя по нажатию кнопки идет инкремент числа, которое отображается в JLabel. Поскольку ширина графического представления чисел разная, у тебя при изменении текста лэйбла будет каждый раз происходить перераскладывание компонентов в соответствии с политикой LayoutManager'а. Если при этом ничего другого на экране не происходит, то ничего страшного. Но что если ты в этот же момент захотел потянуть какой-нибудь сплиттер? Тут и могут произойти нежелательные казусы в виде висячих фрагментов элементов интерфейса (George, ничего, что я говорю по английски? smile Без обид, просто есть такой популярный в иммигрантских кругах анекдот про тетку в русском магазине: "Вам одним писом или послайсить?").

Ну и вот, а если ты хочешь этого избежать, то ты делаешь вот так:

Код

// все остальное как у тебя

          public void run()
          {

            try
            {
              for (int i = 0; i < 99; i++)
              {

//              label.setText("Load: " + i + "%");
                SwingUtilities.invokeLater(new Runnable()
                {
                  public void run()
                  {
                    updateLabel("Load: " + i + "%");
                  }
                });

                sleep(100);
              }
            }
            catch (Exception e)
            {}
         }

// в методах класса
private void updateLabel(String s)
{
  label.setText(s);
}


Тут надо понимать, что тот Runnable, который подсовывается диспетчеру событий, не имет никакого отношения к потоковости. Это просто удобный обобщенный способ вызова некой обезличенной беспараметерной функциональности. Поэтому у тебя будет один run() для твоего потока, где происходят всякие интересные штуки, а другой - для диспетчера, чтобы он знал, как инициировать действия по перерисовке. И произойдет это теперь уже синхронным, а не асинхронным образом.

Так понятнее? smile



--------------------
"If you want something done right, do it yourself"
По секрету: выучить английский - реально!
PM WWW   Вверх
Metal_Heart
Дата 28.4.2005, 11:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


а почему бы и нет?
**


Профиль
Группа: Участник
Сообщений: 728
Регистрация: 31.3.2005
Где: Москва

Репутация: 1
Всего: 12



Спасибо Stampede, хорошо объясняешь, но я как и Lamer George
не люблю буржйских слов в русском, язык должен быть по возможности - чистым
и не важно какой, а смешивать - это не красиво..


--------------------
 не стыдно учиться, а стыдно не учиться 
PM ICQ   Вверх
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   jk1
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, jk1.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: GUI и Java FX приложения | Следующая тема »


 




[ Время генерации скрипта: 0.0608 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.