将Java Gui连接到不同类中的不同实现

时间:2013-08-11 07:26:20

标签: java swing user-interface awt

我正在使用java制作一个简单的java反应游戏。显示是我的类初始化gui:

public class Display extends JFrame实现了Gui {

//Connect gui to controller
//(This method will be called before ANY other methods)
public void connect(Controller controller){

}

    //Initialise the gui
public Display(){
    JPanel panel = new JPanel();
JButton coin = new JButton();
JButton goStop = new JButton();
JLabel prompt = new JLabel("Insert Coin", JLabel.CENTER);

setTitle("Reaction Game");
    setContentPane(panel);

coin.setIcon(new ImageIcon("coin.png"));
goStop.setIcon(new ImageIcon("GoButton.png"));

//setting layout of panel
panel.setLayout(new BorderLayout(100, 20));
//adding buttons to panel
panel.add(prompt, BorderLayout.PAGE_START);
panel.add(coin, BorderLayout.LINE_START);
panel.add(goStop, BorderLayout.LINE_END);


setSize(400,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

}

按钮实际上做的是在两个不同的类中实现,Controller1和Controller2(实现一个Controller类),每个类根据我们决定使用哪一个做不同的事情。

控制器1:

公共类Controller1实现Controller {

//Creating a constructor
public Controller1(){

}
   //Connect controller to gui
//(This method will be called before ANY other methods)
public void connect(Gui gui, Random rng){

}

}

控制器2:

public class Controller2实现Controller {

//Creating a constructor
public Controller2(){

}
   //Connect controller to gui
//(This method will be called before ANY other methods)
public void connect(Gui gui, Random rng){

}

}

我只是想知道如何连接gui和控制器。

1 个答案:

答案 0 :(得分:1)

您可以为执行ActionListenerController1方法的每个按钮创建自定义Controller2。这样,您可以指定将在ActionListener中使用的方法,并将它们分配给特定按钮(或其他GUI组件)。

您可以将以下内容放在Display构造函数中(当然,在初始化coingoStop之后)。

coin.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Controller1 tempcontroller = new Controller1();

        tempcontroller.connect(this, new Random());
    }
});

goStop.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Controller2 tempcontroller = new Controller2();

        tempcontroller.connect(this, new Random());
    }
});