Суббота, 2025-02-08, 00:25:05
Главная Регистрация RSS
Приветствую Вас, Гость
[ Новые сообщения · Участники · Правила форума · Поиск · RSS ]
  • Страница 1 из 1
  • 1
Кофейный автомат
CHerryДата: Воскресенье, 2011-10-30, 23:06:30 | Сообщение # 1
Генералиссимус
Группа: Администраторы
Сообщений: 141
Репутация: 3732
Статус: Offline
Code
package ua.at.javac;

import java.awt.GridLayout;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MakingCoffee {
     // три операции одновременно кофе в фильтр, готовим воду, выдаем стакан
     ExecutorService exec = Executors.newFixedThreadPool(3);
      
     // синхронизация кофе в фильтре с подготовкой воды
     final CyclicBarrier filterAndWater = new CyclicBarrier(2, new Runnable()   
         {
             public void run() {
                 setIndicatorLabel("Кофе и вода подготовлены...");
                 exec.execute(new BrewCoffee());

             }
         }
     );

     // синхронизация свареного кофе с чашкой
     final CyclicBarrier coffeAndGlass = new CyclicBarrier(2, new Runnable()   
         {
             public void run() {
                 setIndicatorLabel("Кофе сварено...");
                 exec.execute(new PourCoffee());
                  
             }
         }
     );

      
      
     private JLabel indicatorLabel    = new JLabel("Выберите напиток");
     private JLabel coffeFilterLabel  = new JLabel("фильтр OK");
     private JLabel coffeWaterLabel   = new JLabel("вода OK");
     private JLabel coffeGlassLabel   = new JLabel("стаканы OK");
     private JLabel drinkLabel        = new JLabel("напитков НЕТ");
     private JLabel drinkOutLabel     = new JLabel("напитков НЕТ");
     private JLabel coffeMachineLabel = new JLabel("машина ОТКЛ");
     private JLabel coffeOutputLabel  = new JLabel("выдачи НЕТ");

     public JLabel getCoffeOutputLabel() {
         return coffeOutputLabel;
     }

     public void setCoffeOutputLabel(String text) {
         coffeOutputLabel.setText(text);
     }

     public JLabel getCoffeMachineLabel() {
         return coffeMachineLabel;
     }

     public void setCoffeMachineLabel(String text) {
         coffeMachineLabel.setText(text);
     }

     public JLabel getDrinkOutLabel() {
         return drinkOutLabel;
     }

     public void setDrinkOutLabel(String text) {
         drinkOutLabel.setText(text);
     }

     public JLabel getDrinkLabel() {
         return drinkLabel;
     }

     public void setDrinkLabel(String text) {
         drinkLabel.setText(text);
     }

     public JLabel getCoffeGlassLabel() {
         return coffeGlassLabel;
     }

     public void setCoffeGlassLabel(String text){
         coffeGlassLabel.setText(text);
     }

     public JLabel getCoffeWaterLabel() {
         return coffeWaterLabel;
     }

     public void setCoffeWaterLabel(String text) {
         coffeWaterLabel.setText(text);
     }

     public JLabel getCoffeFilterLabel() {
         return coffeFilterLabel;
     }

     public void setCoffeFilterLabel(String text) {
         coffeFilterLabel.setText(text);
     }

     public JLabel getIndicatorLabel() {
         return indicatorLabel;
     }

     public void setIndicatorLabel(String text) {
         indicatorLabel.setText(text);
     }

     public static void main (String [] args){
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new MakingCoffee().initGUI();
             }
          });
     }

     // инициализация графического интерфейса
     private void initGUI() {
         // форма
         JFrame frame = new JFrame();
         // кнопка приготовления кофейного напитка в потоке
         JButton makeCoffeeButton = new JButton("Кофе");
         makeCoffeeButton.addActionListener(
                 new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt) {
                         setIndicatorLabel("Приготовление...");
                         exec.execute(new PutFilter());
                         exec.execute(new AddWater());
                         exec.execute(new GetCups());
                     }
                 }
          );

         JButton drinkButton = new JButton("Кола");
         drinkButton.setEnabled(false);

         // создание табличной панели 2 строки * 3 столбца, отступы 10 * 10
         JPanel panel = new JPanel();
         frame.add(panel);
         panel.setLayout(new GridLayout(4,3,10,10));
         panel.add(getIndicatorLabel());
         panel.add(makeCoffeeButton);
         panel.add(drinkButton);
         panel.add(getCoffeFilterLabel());
         panel.add(getCoffeWaterLabel());
         panel.add(getDrinkLabel());
         panel.add(getCoffeGlassLabel());
         panel.add(getCoffeMachineLabel());
         panel.add(getDrinkOutLabel());
         panel.add(getCoffeOutputLabel());

         // свойства формы
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(520, 240);
         frame.setTitle("Кофейный автомат");
         frame.setVisible(true);
     }
   
     class PutFilter implements Runnable{
         @Override
         public void run() {
             // TODO Auto-generated method stub
             for (int i=1; i<=100;i++){
                 setCoffeFilterLabel("Наполняем фильтр "+i+"%");
                 try {
                     TimeUnit.MILLISECONDS.sleep(50);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             setIndicatorLabel("Фильтр наполнен...");
             try {
                 filterAndWater.await();
             } catch (InterruptedException e) {e.printStackTrace();}
             catch (BrokenBarrierException e) {e.printStackTrace();}
         }
     }

     class AddWater implements Runnable{
         @Override
         public void run() {
             // TODO Auto-generated method stub
             for (int i=1; i<=100;i++){
                 setCoffeWaterLabel("Вода "+i+"%");
                 try {
                     TimeUnit.MILLISECONDS.sleep(100);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             setIndicatorLabel("Вода подготовлена...");
             try {
                 filterAndWater.await();
             }
             catch (InterruptedException e) {e.printStackTrace();}
             catch (BrokenBarrierException e) {e.printStackTrace();}
         }
     }

     class GetCups implements Runnable{
         @Override
         public void run() {
             // TODO Auto-generated method stub
             for (int i=1; i<=100;i++){
                 setCoffeGlassLabel("Чашка "+i+"%");
                 try {
                     TimeUnit.MILLISECONDS.sleep(10);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             setIndicatorLabel("Чашка готова...");
             try {
                 coffeAndGlass.await();
             }  
             catch (InterruptedException e) {e.printStackTrace();}
             catch (BrokenBarrierException e) {e.printStackTrace();}
         }
     }
      
     class BrewCoffee implements Runnable{
         @Override
         public void run() {
             // TODO Auto-generated method stub
             for (int i=1; i<=100;i++){
                 setCoffeMachineLabel("Завариваем кофе "+i+"%");
                 try {
                     TimeUnit.MILLISECONDS.sleep(100);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             setIndicatorLabel("Кофе заварено...");
             try {
                 coffeAndGlass.await();
             }  
             catch (InterruptedException e) {e.printStackTrace();}
             catch (BrokenBarrierException e) {e.printStackTrace();}
         }
     }
      

     class PourCoffee implements Runnable{
         @Override
         public void run() {
             // TODO Auto-generated method stub
             for (int i=1; i<=100;i++){
                 setCoffeOutputLabel("Наливаем кофе "+i+"%");
                 try {
                     TimeUnit.MILLISECONDS.sleep(50);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             setCoffeOutputLabel("Кофе в чашке!");
             setIndicatorLabel("Приятного аппетита!");
         }
     }

      
}

 
j_todeskyДата: Пятница, 2011-11-04, 23:52:23 | Сообщение # 2
Рядовой
Группа: Проверенные
Сообщений: 18
Репутация: 1
Статус: Offline
Вов, а зачем подобные лэйблы ???

public JLabel getCoffeOutputLabel() {
return coffeOutputLabel;
}
 
CHerryДата: Суббота, 2011-11-05, 19:14:13 | Сообщение # 3
Генералиссимус
Группа: Администраторы
Сообщений: 141
Репутация: 3732
Статус: Offline
Quote (j_todesky)
ов, а зачем подобные лэйблы ???

public JLabel getCoffeOutputLabel() {
return coffeOutputLabel;
}

Сейчас они не имеют практического назначения.
Их назначение - получение вне класса данных из этих полей (инкапсуляция всех JLabel класса MakingCoffee).
 
  • Страница 1 из 1
  • 1
Поиск: