我正在尝试通过单击 JMenuItem 将 JPanel 添加到我的框架中。我查看了过去的帖子,并尝试使用:
getContentPane().add(myJPanel)
revalidate();
repaint();
无济于事。我的 Game 类现在只是一个具有大小设置和背景颜色的构造函数。哦,抱歉代码乱七八糟,我已经删除了我的非工作原件并迅速完成了这项工作,以了解我尝试过的内容。任何建议将不胜感激。
package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class Main extends JFrame{
static boolean gameActive = false;
Game game;
JMenuBar menuBar;
JMenu file;
JMenuItem startGame;
JMenuItem checkScore;
JMenuItem closeGame;
int userScore;
public Main() {
game = new Game();
gameActive = false;
//set JMenuBar
menuBar = new JMenuBar();
file = new JMenu("File");
startGame = new JMenuItem("Start Game");
checkScore = new JMenuItem("Check Score");
closeGame = new JMenuItem("Close Game");
menuBar.add(file);
file.add(startGame);
file.add(checkScore);
file.add(closeGame);
startGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gameActive = true;
}
});
if(gameActive == true){
getContentPane().add(game);
revalidate();
repaint();
}
checkScore.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(checkScore, "your Score is " + userScore);
}
});
closeGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setJMenuBar(menuBar);
//JFrame Properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setTitle("BattleGrounds");
setResizable(false);
setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Main();
}
});
}
}