[英]where to put ActionListener interface?
我陷入了自己的代码中,用Java编写了游戏GUI。
我有两个包gameCore和view。 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;
}
}
这里有一个例子:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.