1


我不喜欢下面的代码是:

  1. 每个页面上的每个 JButton 都需要 getter
  2. 如果使用 if-else 语句,该actionPerformed方法会很快变得臃肿

那么,有没有更好的方法来控制单个类的所有 GUI 操作?

如果我在 actionPerformed每个相应页面JPanelSingleton


这是代码:

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
4

2 回答 2

2

使用Card Layout. Card Layout Actions添加了一些您可能会觉得有用的额外功能。

于 2013-05-21T04:01:58.197 回答
1

您可以使用卡片布局,也可以发挥创意并删除元素。例如:

panel.remove((JButton)myButton1)); // Remove all of the elements...
panel.add((JButton)myButton2)); // Add the new elements

当然,我根本不会处理内置 GUI 的 java,IMO 布局设计是可怕的。我更愿意使用“新外观”之类的东西——http: //www.javootoo.com/

于 2013-05-21T05:11:15.713 回答