java - 如何在多个类中使用 swing

标签 java model-view-controller swing

我只是想知道一些关于 Swing 的事情 1)如何在swing中使用MVC模型? 2) 假设我有一个主窗口,我需要将菜单作为单独的类,将所有组件作为单独的类,这将是集成它的最佳方法

最佳答案

好的,这被称为过度杀伤力的回答,对此深表歉意,但这是我快速创建的一个示例,它尝试使用简单的 MVC 模式来做一件微不足道的事情:按下一个按钮并更改文本中的文本JTextField。这是大材小用,因为您只需几行代码就可以做同样的事情,但它确实在单独的文件中说明了一些 MVC 以及模型如何控制状态。如果有任何混淆,请提出问题!

将所有内容放在一起并开始工作的主类:

import javax.swing.*;

public class SwingMvcTest {
   private static void createAndShowUI() {

      // create the model/view/control and connect them together
      MvcModel model = new MvcModel();
      MvcView view = new MvcView(model);
      MvcControl control = new MvcControl(model);
      view.setGuiControl(control);

      // EDIT: added menu capability
      McvMenu menu = new McvMenu(control);

      // create the GUI to display the view
      JFrame frame = new JFrame("MVC");
      frame.getContentPane().add(view.getMainPanel()); // add view here
      frame.setJMenuBar(menu.getMenuBar()); // edit: added menu capability
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   // call Swing code in a thread-safe manner per the tutorials
   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

View 类:

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

public class MvcView {
   private MvcControl control;
   private JTextField stateField = new JTextField(10);
   private JPanel mainPanel = new JPanel(); // holds the main GUI and its components

   public MvcView(MvcModel model) {
      // add a property change listener to the model to listen and 
      // respond to changes in the model's state
      model.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent evt) {
            // if the state change is the one we're interested in...
            if (evt.getPropertyName().equals(MvcModel.STATE_PROP_NAME)) {
               stateField.setText(evt.getNewValue().toString()); // show it in the GUI
            }
         }
      });
      JButton startButton = new JButton("Start");
      startButton.addActionListener(new ActionListener() {
         // all the buttons do is call methods of the control
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.startButtonActionPerformed(e); // e.g., here
            }
         }
      });
      JButton endButton = new JButton("End");
      endButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.endButtonActionPerformed(e); // e.g., and here
            }
         }
      });

      // make our GUI pretty
      int gap = 10;
      JPanel buttonPanel = new JPanel(new GridLayout(1, 0, gap, 0));
      buttonPanel.add(startButton);
      buttonPanel.add(endButton);

      JPanel statePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
      statePanel.add(new JLabel("State:"));
      statePanel.add(Box.createHorizontalStrut(gap));
      statePanel.add(stateField);

      mainPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      mainPanel.setLayout(new BorderLayout(gap, gap));
      mainPanel.add(buttonPanel, BorderLayout.CENTER);
      mainPanel.add(statePanel, BorderLayout.PAGE_END);
   }

   // set the control for this view
   public void setGuiControl(MvcControl control) {
      this.control = control;
   }

   // get the main gui and its components for display
   public JComponent getMainPanel() {
      return mainPanel;
   }

}

控件:

import java.awt.event.ActionEvent;

public class MvcControl {
   private MvcModel model;

   public MvcControl(MvcModel model) {
      this.model = model;
   }

   // all this simplistic control does is change the state of the model, that's it
   public void startButtonActionPerformed(ActionEvent ae) {
      model.setState(State.START);
   }

   public void endButtonActionPerformed(ActionEvent ae) {
      model.setState(State.END);
   }
}

该模型使用 PropertyChangeSupport 对象来允许其他对象(在这种情况下为 View)监听状态变化。因此,模型实际上是我们的“可观察对象”,而 View 是“观察者”

import java.beans.*;

public class MvcModel {
   public static final String STATE_PROP_NAME = "State";
   private PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);
   private State state = State.NO_STATE;

   public void setState(State state) {
      State oldState = this.state;
      this.state = state;
      // notify all listeners that the state property has changed
      pcSupport.firePropertyChange(STATE_PROP_NAME, oldState, state);
   }

   public State getState() {
      return state;
   }

   public String getStateText() {
      return state.getText();
   }

   // allow addition of listeners or observers
   public void addPropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.addPropertyChangeListener(listener);
   }

}

一个简单的枚举,State,封装状态的概念:

public enum State {
   NO_STATE("No State"), START("Start"), END("End");
   private String text;

   private State(String text) {
      this.text = text;
   }

   @Override
   public String toString() {
      return text;
   }

   public String getText() {
      return text;
   }
}

编辑:我看到你也提到了菜单,所以我通过添加此类和 SwingMcvTest 类中的几行来添加菜单支持。请注意,由于代码分离,对 GUI 进行此更改是微不足道的,因为所有菜单需要做的就是调用控制方法。它不需要对模型或 View 一无所知:

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

public class McvMenu {
   private JMenuBar menuBar = new JMenuBar();
   private MvcControl control;

   @SuppressWarnings("serial")
   public McvMenu(MvcControl cntrl) {
      this.control = cntrl;

      JMenu menu = new JMenu("Change State");
      menu.add(new JMenuItem(new AbstractAction("Start") {
         public void actionPerformed(ActionEvent ae) {
            if (control != null) {
               control.startButtonActionPerformed(ae);
            }
         }
      }));
      menu.add(new JMenuItem(new AbstractAction("End") {
         public void actionPerformed(ActionEvent ae) {
            if (control != null) {
               control.endButtonActionPerformed(ae);
            }
         }
      }));

      menuBar.add(menu);
   }

   public JMenuBar getMenuBar() {
      return menuBar;
   }
}

上帝啊,做一些微不足道的事情需要很多代码!我提名我自己和我的代码参加本周的 stackoverflow Rube Goldberg 奖。

关于java - 如何在多个类中使用 swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6087436/

相关文章:

java - 查找两点之间的角度时出错

java - 如何在背压期间仅缓冲来自 rx.Observable 的最新发射

java - 将 UMLS 用户名和密码添加到 Ctakes

java - Hazelcast - .Net 客户端支持可靠的主题吗?

c# - mvc 根据模型值更改表列颜色

java - 将关键监听器添加到 JtextArea

java - 购物车的OO设计模式

java - 模型、 View 和 Controller ——应该创建什么?

php - 高流量网站的推荐结构

java - 有没有办法实时和手动更新 JLabel 文本?