我不喜欢什么我下面的代码是:需要为每一个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 –