我目前正在開發自己的掃雷艇。 Swing遵循模型 - 視圖 - 控制器設計模式。在MVC,我學會了每當模型發生變化時,控制器將在視圖中觸發該變化。但在這個例子中,我無法追蹤如何使setTitle
和setInfo
中的更改得到反映。在模型 - 視圖 - 控制器中,爲什麼在模型中改變,不會觸發視圖中的改變?
這裏,當我設置對話框的標題時,實際內容(模型)正在發生變化,但輸出(視圖)中沒有相應的更改。
//InfoDisplayer is inner class of class MenuActionListener
class InfoDisplayer extends JDialog {
JLabel info;
BorderLayout infoBorderLayout = new BorderLayout();
public InfoDisplayer(JFrame ownerFrame) {
super(ownerFrame,true);
info = new JLabel();
setFocusable(false);
setSize(300,400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(infoBorderLayout);
add(info,BorderLayout.SOUTH);
setVisible(true);
}
void setInfo(JLabel info) {
this.info = info;
}
public void setTitle(String title) {
super.setTitle(title);
}
}
if ((event.getActionCommand()).equals("HowToPlay")) {
InfoDisplayer instructionsDisplay = new InfoDisplayer(gUIManagerFrame);
//gUIManagerFrame is an object of its outer class,MenuActionListener
instructionsDisplay.setTitle("INSTRUCTIONS");
instructionsDisplay.setInfo(new JLabel("<html><h1><B>INSTRUCTIONS</B></h1></html>"));
} else {// if about is clicked!!
InfoDisplayer aboutDisplay = new InfoDisplayer(gUIManagerFrame);
aboutDisplay.setTitle("MineSweeper v0.1");
aboutDisplay.setInfo(new JLabel("<html><h1><B>MineSweeperv1.0</B></h1> </html>"));
}
關於MVC的任何關鍵詞? –
兩種方式都沒有工作。您將如何移除舊的JLabel並添加新的JLabel? \t \t \t \t \t月1日:「無效setInfo(JLabel的信息){ \t \t \t \t \t \t刪除(這一點。信息); \t \t \t \t \t \t this.info.setText(info.toString()); \t \t \t \t add(this.info,BorderLayout.SOUTH); \t \t \t \t \t} 「第二: 」 \t \t \t \t \t空隙setInfo(JLabel的信息){ \t \t \t \t \t \t刪除(this.info); \t \t \t \t \t \t this.info = info; \t \t \t \t \t add(info,BorderLayout.SOUTH); \t \t \t \t \t}」 –
+1用於更新替換以上;更多的MVC [這裏](http://stackoverflow.com/a/8401255/230513) – trashgod