簡體   English   中英

如何在Java Swing應用程序中管理控制器的視圖更新

[英]How to manage view updates from controllers in a Java Swing app

我發現用Swing編寫好的OO代碼非常難。 我的問題基本上是我有一個有動作監聽器的視圖(JPanel)。 動作偵聽器確定單擊了哪個按鈕並調用適當的控制器方法。 問題是此控制器方法需要更新另一個視圖。 所以我遇到的問題是我將視圖傳遞給控制器​​。 這是一個例子。

public class MyView extends JPanel implements ActionListener {
  private final MyController controller = new MyController();

  @Override public void actionPerformed(ActionEvent e) {
    this.controller.updateOtherView();
  }
}

這基本上就是我想要的,但這就是最終發生的事情。

public class MyView extends JPanel implements ActionListener {
  private MyController controller = new MyController();
  private OtherView otherView;

  public MyView(MyOtherView otherView) {
    this.otherView = otherView;
  }

  @Override public void actionPerformed(ActionEvent e) {
    this.controller.updateOtherView(otherView);
  }
}

您可以看到,隨着需要更新的視圖數量的增加以及看起來像這樣的類數量的增加,視圖本質上是全局變量,代碼變得復雜且不清楚。 我遇到的另一個問題是這個其他視圖通常沒有直接傳遞到MyView,但它必須通過MyView的父級才能進入MyView,這真的只是讓我煩惱。

對於一個真實的例子,假設我有一個菜單和這個MyView。 MyView有一個播放按鈕,可播放一段時間的音樂,並禁用(灰顯)播放按鈕,直到音樂結束。 如果我有一個名為play的菜單選項,現在我需要訪問其他視圖播放按鈕,這樣我就可以將它變灰了。 如果沒有這種煩人的意見傳遞,我該怎么做呢? 雖然可能有針對此問題的特定解決方案,但我正在尋找能夠解決一般情況下此視圖訪問問題的方法。

我根本不確定如何解決這個問題。 我現在正在使用MVC模式術語而不使用MVC模式,這可能是也可能不是必需的。 任何幫助表示贊賞。

一種解決方案:只需讓控制器更新模型即可。 然后附加到模型的偵聽器將更新視圖。 您還可以讓JMenuItems和相應的JButton共享相同的Action,因此當您禁用Action時,它將禁用使用該Action的所有按鈕/菜單/等。

例如,主類:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MvcExample {

   private static void createAndShowGui() {
      MyView view = new MyView();
      MyMenuBar menuBar = new MyMenuBar();
      MyModel model = new MyModel();
      MyControl control = new MyControl(model);
      control.addProgressMonitor(view);
      control.addView(view);
      control.addView(menuBar);

      model.setState(MyState.STOP);

      JFrame frame = new JFrame("MVC Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(view.getMainPanel());
      frame.setJMenuBar(menuBar.getMenuBar());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

   private static final byte[] DATA_ARRAY = { 0x43, 0x6f, 0x70, 0x79, 0x72,
         0x69, 0x67, 0x68, 0x74, 0x20, 0x46, 0x75, 0x62, 0x61, 0x72, 0x61,
         0x62, 0x6c, 0x65, 0x2c, 0x20, 0x30, 0x36, 0x2f, 0x31, 0x36, 0x2f,
         0x32, 0x30, 0x31, 0x32, 0x2e, 0x20, 0x46, 0x75, 0x62, 0x61, 0x72,
         0x61, 0x62, 0x6c, 0x65, 0x20, 0x52, 0x75, 0x6c, 0x65, 0x73, 0x21 };

}

控制:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;

@SuppressWarnings("serial")
public class MyControl {
   private MyModel model;
   private PlayAction playAction = new PlayAction();
   private PauseAction pauseAction = new PauseAction();
   private StopAction stopAction = new StopAction();
   private List<MyProgressMonitor> progMonitorList = new ArrayList<MyProgressMonitor>();

   public MyControl(MyModel model) {
      this.model = model;

      model.addPropertyChangeListener(new MyPropChangeListener());
   }

   public void addProgressMonitor(MyProgressMonitor progMonitor) {
      progMonitorList.add(progMonitor);
   }

   public void addView(MySetActions setActions) {
      setActions.setPlayAction(playAction);
      setActions.setPauseAction(pauseAction);
      setActions.setStopAction(stopAction);
   }

   private class MyPropChangeListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent pcEvt) {
         if (MyState.class.getName().equals(pcEvt.getPropertyName())) {
            MyState state = (MyState) pcEvt.getNewValue();

            if (state == MyState.PLAY) {
               playAction.setEnabled(false);
               pauseAction.setEnabled(true);
               stopAction.setEnabled(true);
            } else if (state == MyState.PAUSE) {
               playAction.setEnabled(true);
               pauseAction.setEnabled(false);
               stopAction.setEnabled(true);
            } else if (state == MyState.STOP) {
               playAction.setEnabled(true);
               pauseAction.setEnabled(false);
               stopAction.setEnabled(false);
            }
         }
         if (MyModel.PROGRESS.equals(pcEvt.getPropertyName())) {
            for (MyProgressMonitor progMonitor : progMonitorList) {
               int progress = (Integer) pcEvt.getNewValue();
               progMonitor.setProgress(progress);
            }            
         }
      }
   }

   private class PlayAction extends AbstractAction {
      public PlayAction() {
         super("Play");
         putValue(MNEMONIC_KEY, KeyEvent.VK_P);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         model.play();
      }
   }

   private class StopAction extends AbstractAction {
      public StopAction() {
         super("Stop");
         putValue(MNEMONIC_KEY, KeyEvent.VK_S);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         model.stop();
      }
   }
   private class PauseAction extends AbstractAction {
      public PauseAction() {
         super("Pause");
         putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         model.pause();
      }
   }
}

國家枚舉:

public enum MyState {
   PLAY, STOP, PAUSE
}

其中一個視圖界面:

import javax.swing.Action;

public interface MySetActions {

   void setPlayAction(Action playAction);
   void setPauseAction(Action pauseAction);
   void setStopAction(Action stopAction);
}

另一個視圖界面:

public interface MyProgressMonitor {
   void setProgress(int progress);
}

主GUI視圖:

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class MyView implements MySetActions, MyProgressMonitor {
   private JButton playButton = new JButton();
   private JButton stopButton = new JButton();
   private JButton pauseButton = new JButton();
   private JPanel mainPanel = new JPanel();
   private JProgressBar progressBar = new JProgressBar();

   public MyView() {
      progressBar.setBorderPainted(true);

      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      btnPanel.add(playButton);
      btnPanel.add(pauseButton);
      btnPanel.add(stopButton);

      mainPanel.setLayout(new BorderLayout(0, 5));
      mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
      mainPanel.add(btnPanel, BorderLayout.CENTER);
      mainPanel.add(progressBar, BorderLayout.PAGE_END);
   }

   @Override
   public void setPlayAction(Action playAction) {
      playButton.setAction(playAction);
   }

   @Override
   public void setStopAction(Action stopAction) {
      stopButton.setAction(stopAction);
   }

   @Override
   public void setPauseAction(Action pauseAction) {
      pauseButton.setAction(pauseAction);
   }

   @Override
   public void setProgress(int progress) {
      progressBar.setValue(progress);
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

}

View的菜單欄部分:

import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MyMenuBar implements MySetActions {
   private JMenuItem playMenItem = new JMenuItem();
   private JMenuItem pauseMenuItem = new JMenuItem();
   private JMenuItem stopMenItem = new JMenuItem();
   private JMenuBar menuBar = new JMenuBar();

   public MyMenuBar() {
      JMenu menu = new JMenu("Main Menu");
      menu.setMnemonic(KeyEvent.VK_M);
      menu.add(playMenItem);
      menu.add(pauseMenuItem);
      menu.add(stopMenItem);
      menuBar.add(menu);
   }

   public JMenuBar getMenuBar() {
      return menuBar;
   }

   @Override
   public void setPlayAction(Action playAction) {
      playMenItem.setAction(playAction);
   }

   @Override
   public void setStopAction(Action stopAction) {
      stopMenItem.setAction(stopAction);
   }

   @Override
   public void setPauseAction(Action pauseAction) {
      pauseMenuItem.setAction(pauseAction);
   }

}

最后,模型:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import javax.swing.Timer;
import javax.swing.event.SwingPropertyChangeSupport;

public class MyModel {
   public final static String PROGRESS = "progress";
   protected static final int MAX_PROGRESS = 100; 
   private MyState state = null;
   private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
         this);
   private Timer timer;
   private int progress = 0;

   public MyState getState() {
      return state;
   }

   public void setState(MyState state) {
      MyState oldValue = this.state;
      MyState newValue = state;
      this.state = newValue;
      pcSupport.firePropertyChange(MyState.class.getName(), oldValue, newValue);
   }

   public int getProgress() {
      return progress;
   }

   public void setProgress(int progress) {
      Integer oldValue = this.progress;
      Integer newValue = progress;
      this.progress = newValue;
      pcSupport.firePropertyChange(PROGRESS, oldValue, newValue);
   }

   public void play() {
      MyState oldState = getState();
      setState(MyState.PLAY);

      if (oldState == MyState.PAUSE) {
         if (timer != null) {
            timer.start();
            return;
         }
      }
      int timerDelay = 50;
      // simulate playing ....
      timer = new Timer(timerDelay, new ActionListener() {
         int timerProgress = 0;

         @Override
         public void actionPerformed(ActionEvent actEvt) {
            timerProgress++;
            setProgress(timerProgress);
            if (timerProgress >= MAX_PROGRESS) {
               setProgress(0);
               MyModel.this.stop();
            }
         }
      });
      timer.start();
   }

   public void pause() {
      setState(MyState.PAUSE);
      if (timer != null && timer.isRunning()) {
         timer.stop();
      }
   }

   public void stop() {
      setState(MyState.STOP);
      setProgress(0);
      if (timer != null && timer.isRunning()) {
         timer.stop();
      }
      timer = null;
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.removePropertyChangeListener(listener);
   }
}

請問一下這是否有點混亂。

在這種情況下,我傾向於使用單身人士。 當然,這取決於您的觀點的獨特性。 我通常為我的“窗戶”(JFrames)擁有單身人士,所以我可以通過使用getter從那些導航到我需要的任何孩子。 然而,在非常復雜的情況下,這可能不是最好的主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM