我试图让它显示一个 JPanel 并删除另一个取决于 java 中哪个计时器关闭。这是代码的片段。mainMenu 和 pongField 是 JPanel,这是在每毫秒执行一次的计时器内;
if (SwingUtilities.getAncestorOfClass(JFrame.class, pongField) != null){
if (!pongField.getTimer().isRunning())
{
mainMenu = new MainMenu(screenX, screenY, myColor, background, contentPane);
contentPane.remove(pongField);
}}
if (SwingUtilities.getAncestorOfClass(JFrame.class, mainMenu) != null){
if (!mainMenu.getTimer().isRunning())
{
switch(mainMenu.getButton())
{
case 1:
pongField = new PongField(screenX, screenY, 0, moderator, player1UpControl, player2UpControl, player1DownControl, player2DownControl, myColor, background, contentPane, speed);
mainMenu.setButton(0);
contentPane.remove(mainMenu);
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}}
让我更具体一点。我正在尝试制作 Pong,一个 JPanel 是实际游戏,另一个是主菜单。如果游戏结束计时器停止并且如果我按下主菜单上的按钮计时器停止并将 getButton() 设置为取决于按下的数字。例如,如果按下按钮单人玩家,它会创建游戏并摆脱当前的 Jpanel。但如果游戏结束,它会摆脱当前的 JPanel 并显示主菜单。此外,每个 JPanel 在创建时都会设置它自己的边界、背景颜色,并将其自身添加到 JFrame。
问题是当我运行它并且游戏结束时它不会变回来,除非我将它最小化并重新启动它,但然后按钮将不起作用。这是 MainMenu 的代码。PongField 的代码太长,但我想我总结了它做得足够好的地方,但如果你愿意,我也可以发布它。
公共类 MainMenu 扩展 JPanel { private static final long serialVersionUID = 1L;
//JButtons
private JButton singleJButton, multiJButton, settingsJButton, exitJButton;
//timer if game is still on
private Timer runningTimer;
//JLabel for title
private JLabel titleJLabel;
//screen size
int screenX, screenY;
//color of text and background
private Color myColor, background;
//Container of the JFrame
private Container contentPane;
//which button was clicked
private int buttonPressed;
public MainMenu(int x, int y, Color myC, Color backg, Container contentP)
{
super();
//Initialize all given variables
screenX = x;
screenY = y;
myColor = myC;
background = backg;
contentPane = contentP;
setBounds(0,0,screenX,screenY);
setBackground(background);
contentPane.add(this);
setFocusable(true);
requestFocusInWindow();
singleJButton = new JButton();
singleJButton.setBounds(100, 100, 100, 50);
singleJButton.setText("Single Player");
singleJButton.setFocusable(false);
contentPane.add(singleJButton);
singleJButton.addActionListener(new ActionListener()
{public void actionPerformed( ActionEvent event )
{singleJButtonAction(event);}});
runningTimer = new Timer( 30, new ActionListener()
{public void actionPerformed( ActionEvent event )
{}});
runningTimer.start();
}
public Timer getTimer()
{
return runningTimer;
}
public int getButton()
{
return buttonPressed;
}
public void setButton(int val)
{
buttonPressed = val;
}
private void singleJButtonAction(ActionEvent e)
{
runningTimer.stop();
buttonPressed = 1;
}
//make this panel have focus
public void focus()
{
requestFocusInWindow();
}