[英]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.