我不喜歡什麼我下面的代碼是:需要爲每一個JButton用於在GUI頁面之間切換的建議設計模式是什麼?
- 干將每一頁
- 在
actionPerformed
方法很快就會變得臃腫if-else語句
那麼,有沒有更好的方法來控制一個類的所有GUI操作?
如果我定義每個相應頁面(JPanel
)內的actionPerformed
方法,每一頁將需要訪問的頁面(一個或多個)的情況下切換到,和我使用每個頁面的Singleton
圖案試圖避免。 ..
下面是代碼:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* @author Ian A. Campbell
*
*/
public class Controller implements ActionListener {
/**
* instance variables:
*/
private Frame frame;
private OptionPage firstPage;
private FirstOptionPage firstOption;
private SecondOptionPage secondOption;
/**
*
*/
public Controller() {
// instantiating the frame here:
this.frame = new Frame();
/*
* instantiating all pages here:
*
* NOTE: passing "this" because this class
* handles the events from these pages
*/
this.firstPage = new OptionPage(this);
this.firstOption = new FirstOptionPage(this);
this.secondOption = new SecondOptionPage(this);
}
/**
*
*/
public void start() {
this.frame.add(this.firstPage); // adding the first page
// NOTE: these lines prevent blank loading and flickering pages!
this.frame.validate();
this.frame.repaint();
this.frame.setVisible(true);
}
/**
*
* @return the JFrame instantiated from the class Frame
*/
public Frame getFrame() {
return this.frame;
}
@Override
public void actionPerformed(ActionEvent e) {
// the "first option" button from the OptionPage:
if (e.getSource() == this.firstPage.getFirstButton()) {
this.frame.getContentPane().removeAll();
this.frame.getContentPane().add(this.firstOption);
// the "second option" button from the OptionPage:
} else if (e.getSource() == this.firstPage.getSecondButton()) {
this.frame.getContentPane().removeAll();
this.frame.getContentPane().add(this.secondOption);
}
// NOTE: these lines prevent blank loading and flickering pages!
this.frame.validate();
this.frame.repaint();
this.frame.setVisible(true);
}
} // end of Controller
你正在嘗試構建的東西叫做嚮導。也許這會有所幫助。 http://www.oracle.com/technetwork/articles/javase/wizard-136789.html –