我经常使用 Martin Fowler 的演示模型模式来实现我的 Java swing GUI 。
这是一个例子:
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
interface MainView {
void configurationButtonAddActionListener(ActionListener actionListener);
void directoryLabelSetText(String text);
ListModel fileListGetModel();
void setVisible(final boolean visible);
}
class MainFrame
extends JFrame
implements MainView {
private final JButton configurationButton = new JButton("Configuration...");
private final JLabel directoryLabel = new JLabel();
private final JList fileList = new JList();
public MainFrame(final String title) {
super(title);
final JPanel mainPanel = new JPanel(new BorderLayout());
add(mainPanel);
mainPanel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
mainPanel.add(directoryLabel, BorderLayout.NORTH);
mainPanel.add(new JScrollPane(fileList));
mainPanel.add(configurationButton, BorderLayout.SOUTH);
setSize(800, 600);
setLocationRelativeTo(null);
}
@Override
public void configurationButtonAddActionListener(final ActionListener actionListener) {
configurationButton.addActionListener(actionListener);
}
@Override
public void directoryLabelSetText(final String text) {
directoryLabel.setText(text);
}
@Override
public ListModel fileListGetModel() {
return fileList.getModel();
}
}
然后可以将接口传递给负责处理视图上的所有操作的演示者类。可以将模拟版本传递给演示者进行测试,并且视图非常简单,理论上不需要进行单元测试。
我正在尝试在 Clojure 中使用以下方法做类似的事情defrecord
:
(ns mainframe
(:gen-class)
(:import
[java.awt BorderLayout]
[javax.swing JButton JFrame JLabel JList JPanel JScrollPane]))
(if *compile-files*
(set! *warn-on-reflection* true))
(defprotocol MainView
(directory-label-set-text [this text])
(set-visible [this visible]))
(defrecord mainframe [^JFrame frame
directory-label
file-list
configuration-button]
MainView
(directory-label-set-text [this text]
(.setText directory-label text))
(set-visible [this visible]
(.setVisible frame visible)))
(defn create-main-frame
[title]
(let [directory-label (JLabel.)
file-list (JList.)
configuration-button (JButton. "Configuration...")
main-panel (doto (JPanel. (BorderLayout.))
(.add directory-label BorderLayout/NORTH)
(.add (JScrollPane. file-list))
(.add configuration-button BorderLayout/SOUTH))
frame (doto (JFrame.)
(.setTitle title)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.add main-panel)
(.setSize 800 600)
(.setLocationRelativeTo nil))]
(mainframe. frame directory-label file-list configuration-button)))
我可以做界面和“类”的唯一方法是使用defprotocol
and defrecord
。有没有更好的办法?有什么方法可以使defrecord
包含组件(JButton、JLabel、JList)的“字段”私有?我不喜欢暴露实现细节。