因此,我有一个扩展 a 的类,JPanel
并在构造函数中添加我的JButtons
以及我需要添加的任何其他内容。我还有一个MainFrame
容器JFrame
类FrameSwitcher
(MainFrame
我在这样做时遇到了麻烦,我找不到合适的方法来做到这一点。我也希望保持 JButtons 私有和非静态。
JPanel 示例:
public class MainMenu() {
private JButton btnSinglePlayer, btnMultiPlayer;
public MainMenu() {
setLayout(null);
btnSinglePlayer = new JButton("singlePlayer");
btnSinglePlayer.setBounds(320, 25, 275, 130);
add(btnSinglePlayer);
btnMultiPlayer = new JButton("MultiPlayer");
btnMultiPlayer.setBounds(320, 170 , 275, 130);
add(btnMultiPlayer);
}
}
帧切换器:
public class FrameSwitcher implements panelListener { // panelListener is an interface defined else where.
public FrameSwitcher(MainFrame frame) {
// This is irrelevant to the question.
}
@Override
public void gamePanel() {
System.out.println("GamePanel Event: Recieved");
}
@Override
public void mainMenu() {
System.out.println("mainMenu Event: Recieved");
}
@Override
public void scoreBoardPanel() {
System.out.println("scoreBoardPanel Event: Recieved");
}
}
然后是我的 MainFrame:
public class MainFrame extends JFrame implements ActionListener {
private PanelListener panelListener;
private JFrame mainContainer = new JFrame("Game");
private JPanel mainMenu = new MainMenu();
public void start() {
mainContainer(mainMenu);
}
public MainFrame(JPanel frame) {
mainContainer.getContentPane().add(frame);
mainContainer.pack();
// Other methods to initialize the frame
return mainContainer;
}
public void switchFrames(PanelListener panelListener) {
this.panelListener = panelListener; // PanelListener is an interface.
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getsource();
if(source == MainMenu.btnSinglePlayer) {
if(panelListener != null) {
System.out.println("Recieved the event approriately.");
}
}
}
}
在这个例子中,它确实编译了,但没有做它应该做的事情。另一件事是我目前将 JButtons 作为公共和静态的,我不希望这样。