그래서 JPanel
을 확장하는 클래스가 있고 생성자 내에서 JButtons
을 추가하고 추가해야 할 것은 무엇이든 추가합니다. 나는 또한 용기 (JFrame
) 인 MainFrame
클래스가이 클래스는 클릭했는지 버튼을 평가하고 내가 해요 MainFrame
다른 클래스에서 JButton을 관찰하는 방법?
에 정보를 전달하는 것이다 FrameSwitcher
(컨트롤러)라는 클래스에서 인수를 취할 것 이 일을하는 데 어려움을 겪고 있는데, 나는 이것을 할 수있는 적절한 방법을 찾을 수 없습니다. 또한 JButton을 비공개 및 비 정적으로 유지하고자합니다.
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);
}
}
FrameSwitcher : 그것은
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.");
}
}
}
}
이 예에서, 그것은 컴파일 않지만,하지 않습니다 무엇 :
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");
}
}
그런 다음 내 메인 프레임
그럴거야. 또 다른 것은 공공 및 정적 JButton을 현재 보유하고 있다는 것입니다.
는'actionPerformed'이'MainFrame' 클래스는 현재 구현하지 않는'ActionListener' 인터페이스의 방법으로 해당 메뉴 리스너 이벤트를 해고 .. 그래서, 당신은 무엇을 기대 했습니까? 이 전체 디자인은 엉망입니다. 기본 사항으로 돌아갑니다. – mre
ActionListener를 FrameSwitcher 클래스에 구현하고 MainMenu 클래스에서 각 버튼에 ActionListener (FrameSwitcher)를 추가합니다. –