Я пытаюсь добавить JPanel в свой кадр по клику JMenuItem. Я смотрел в прошлых постах, и я попытался его с помощью:Добавить JPanel в фрейм, используя оператор if
getContentPane().add(myJPanel)
revalidate();
repaint();
безрезультатно. Класс My 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();
}
});
}
}
Это было ошеломляюще легко, спасибо Reimeus! –
Np, добро пожаловать :) – Reimeus