在哪里放置ActionListener接口?

时间:2017-02-09 08:59:04

标签: java swing

我陷入了我的代码,用Java制作游戏GUI。

我有两个包gameCore和视图。 GameCore由“main”组成,我在其中构造了从视图包导入的JFrame对象。

在视图包中,我创建了MainFrame和ControlView类。

在MainFrame的构造函数中,它将调用“setControlView”方法,然后在mainFrame上添加“getControlView()。getControlPanel()”。

因此,我想链接到ActionListener的按钮位于“controlPanel”

我尝试了很多位置来实现ActionListener接口,但我仍然无法解决问题。

我应该在GameCore主类上实现吗?还是在任何地方?

package view;

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {

    private MainFrame console;
    private ControlView controlView;
    private PlayView playView;

    public MainFrame(String title) throws HeadlessException {

        super(title);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(350, 350);
        this.setControlView();
        this.add(getControlView().getControlPanel());
        this.setVisible(true);

    }

    public void setControlView() {
        this.controlView = new ControlView();
    }

    public void setPlayView() {
        this.playView = new PlayView();
    }

    public MainFrame getConsole() {
        return console;
    }

    public ControlView getControlView() {
        return controlView;
    }

}

package view;

import javax.swing.*;
import java.awt.*;

/**
 * Created by hyunjung on 09/02/2017.
 */
public class ControlView extends JPanel {

    private JPanel controlPanel;
    private JLabel titleLabel;
    private JLabel creditLabel;
    private JPanel btnPanel;

    private JButton playBtn;
    private JButton recordBtn;


    public ControlView () {

        controlPanel = new JPanel();
        controlPanel.setBackground(new Color(143, 225, 81));
        controlPanel.setLayout(new GridLayout(3, 1));

        titleLabel = new JLabel("BLACK JACK 2017", JLabel.CENTER);
        titleLabel.setFont(new Font("serif", Font.BOLD, 20));

        creditLabel = new JLabel("@pretty_much games", JLabel.CENTER);
        creditLabel.setFont(new Font("serif", Font.PLAIN, 14));

        btnPanel = new JPanel( new GridBagLayout());
        btnPanel.setBackground(new Color(143, 225, 81));
        playBtn = new JButton("Play");
        recordBtn = new JButton("Record");

        btnPanel.add(playBtn);
        btnPanel.add(recordBtn);

        controlPanel.add(titleLabel);
        controlPanel.add(btnPanel);
        controlPanel.add(creditLabel);
    }

    public JPanel getControlPanel() {
        return controlPanel;
    }

    public JButton getPlayBtn() {
        return playBtn;
    }

    public JButton getRecordBtn() {
        return recordBtn;
    }
}

1 个答案:

答案 0 :(得分:0)

这里有一个例子:

playBtn.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub  
    }

});

这必须在初始化按钮后实现。所以在这个代码块中有意义:

playBtn = new JButton("Play");
recordBtn = new JButton("Record");

btnPanel.add(playBtn);
btnPanel.add(recordBtn);