JMenuItems not responding - java

I have created a 3x3 memory game with colors. The program runs and displays the colors, but the JMenuBar is not working correctly. The button new board, play and end game are not working. Is there something wrong with my Actionlistener?
This is how the code should be working : https://gyazo.com/9bf3e073a9c455e56d9b4403586bfaf5?fbclid=IwAR3Zk1BZvRj49CtAz01h95zic8tk74UmyUcU2HrY3VY8XcARoD14Ke6tcoQ
This is StartPlayer
import gui.MemoryGameWindow;
import gui.ColoredPanel;
import gui.GamePanel;
public class StartPlayer {
public static void main(String[] args) {
new MemoryGameWindow();
}
}
This is ColoredPanel
package gui;
import java.awt.Color;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class ColoredPanel extends JPanel {
private Color thisColor = null;
private Color challenge = null;
public ColoredPanel(Color color) {
this.thisColor = color;
setBackground(color);
}
public void setGameMode(Color c, MouseListener ml) {
setBackground(Color.LIGHT_GRAY);
this.challenge = c;
System.out.println("Coloredpanel says challenge is " + this.challenge);
addMouseListener(ml);
}
public void restoreBackground() {
setBackground(this.thisColor);
}
}
This is GamePanel
package gui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private Color[] colors = new Color[] { Color.GREEN, Color.YELLOW, Color.MAGENTA };
private Random r = new Random();
private int square = 9;
private Color challenge;
private int countOfPossibleHits = 0;
private int countOfWinnerHits = 0;
private JPanel challengeDisplay;
public GamePanel(JPanel cd) {
this.challengeDisplay = cd;
setLayout(new GridLayout(3, 0, 2, 2));
for (int i = 0; i < this.square; i++)
add(new ColoredPanel(this.colors[this.r.nextInt(this.colors.length)]));
}
public Color startGame() {
Color[] existingColors = new Color[getComponentCount()];
int i;
for (i = 0; i < getComponentCount(); i++)
existingColors[i] = ((ColoredPanel)getComponent(i)).getBackground();
this.challenge = existingColors[this.r.nextInt(existingColors.length)];
this.countOfPossibleHits = 0;
for (i = 0; i < getComponentCount(); i++) {
if (((ColoredPanel)getComponent(i)).getBackground() == this.challenge)
this.countOfPossibleHits++;
}
for (i = 0; i < getComponentCount(); i++)
((ColoredPanel)getComponent(i)).setGameMode(this.challenge, new TheMouselistener());
return this.challenge;
}
class TheMouselistener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
ColoredPanel clickedObject = (ColoredPanel)e.getSource();
clickedObject.restoreBackground();
if (clickedObject.getBackground() != GamePanel.this.challenge) {
clickedObject.add(new JLabel("Game Over!"));
GamePanel.this.challengeDisplay.add(new JLabel("Game Over!"));
System.out.println("Game Over");
GamePanel.this.updateUI();
} else {
GamePanel.this.countOfWinnerHits = GamePanel.this.countOfWinnerHits + 1;
if (GamePanel.this.countOfWinnerHits == GamePanel.this.countOfPossibleHits) {
clickedObject.add(new JLabel("You won!"));
GamePanel.this.challengeDisplay.add(new JLabel("You Won!"));
GamePanel.this.updateUI();
}
}
}
}
}
This is MemoryGameWindow
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
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.JPanel;
public class MemoryGameWindow extends JFrame implements ActionListener {
private JMenuItem newgame = null;
private JMenuItem playgame = null;
private JMenuItem exit = null;
private GamePanel gamepanel = null;
private JPanel challengeDisplay;
public MemoryGameWindow() {
setTitle("memory game");
setLayout(new BorderLayout(5, 5));
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
setJMenuBar(new GameMenubar(this));
setSize(600, 600);
setLocationRelativeTo((Component)null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object s = e.getSource();
if (s == this.newgame) {
remove(this.gamepanel);
remove(this.challengeDisplay);
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
this.playgame.setEnabled(true);
this.gamepanel.updateUI();
}
if (s == this.playgame) {
Color challenge = this.gamepanel.startGame();
this.challengeDisplay.setBackground(challenge);
this.playgame.setEnabled(false);
this.gamepanel.updateUI();
}
if (s == this.exit)
System.exit(0);
}
class GameMenubar extends JMenuBar {
public GameMenubar(MemoryGameWindow memoryGameWindow) {
JMenu file;
add(file = new JMenu("File"));
MemoryGameWindow.this.newgame = new JMenuItem("new board");
file.add(new JMenuItem("new board"));
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
MemoryGameWindow.this.exit = new JMenuItem("end program");
file.add(new JMenuItem("end program"));
MemoryGameWindow.this.newgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.playgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.exit.addActionListener(memoryGameWindow);
}
}
}

Have a look at these two lines:
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
First, you set the value of playgame to new JMenuItem. Later in the code, you add an ActionListener to it. That is all correct.
The problem is, the JMenuItem with the ActionListener added to it is not what you’re adding to the menu bar. Instead, you’re adding a brand new JMenuItem, which has no ActionListeners added to it.
The fix is as simple as:
file.add(MemoryGameWindow.this.playgame);
Obviously, you will need to do this for your other menu items too.

Related

Why is my GUI not showing up? I am trying to make a tic tac toe board but my GUI is not showing up

I am trying to make a tic tac toe game in java but my GUI is just not showing up. It makes a board and you are able to press buttons to play tic tac toe. I am new to java so I have no idea what is wrong. It has no errors and I use repl. What is wrong?
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel panel = new JPanel();
private XOButtons[] buttons = new XOButtons[9];
private int turn = 0;
#Override
public void actionPerformed(ActionEvent actionEvent) {
XOButtons source = (XOButtons)actionEvent.getSource();
if(turn == 0){
source.toggleX();
setTitle("O Turn");
} else if(turn == 1){
source.toggleO();
setTitle("X's Turn");
}
turn = (turn + 1) % 2;
}
public static void main(String[] args) {
new TicTacToe();
}
public void TicTacToe() {
setTitle("Tic Tac Toe");
setSize(600,600);
setLocation(100,100);
getContentPane().setBackground(Color.CYAN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(new GridLayout(3,3,5,5));
panel.setBackground(Color.BLUE);
for(int i=0; i < buttons.length; i++) {
buttons[i] = new XOButtons();
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
add(panel);
setVisible(true);
}
}
Here is my second java file:
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class XOButtons extends JButton {
private static final long serialVersionUID = 1L;
private ImageIcon xIcon = new ImageIcon(getClass().getResource("x.png"));
private ImageIcon oIcon = new ImageIcon(getClass().getResource("o.png"));
public void toggleX() {
if(getIcon() == null) {
setIcon(xIcon);
} else {
setIcon(null);
}
}
public void toggleO() {
if(getIcon() == null) {
setIcon(oIcon);
} else {
setIcon(null);
}
}
}
Also, I have x.png and o.png loaded in.
There are a few problems and less than optimal ways of solving the problem in that code, but this problem was caused by turning the class name (TicTacToe) into Main and changing the constructor into a method.
This is what results when that is corrected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class TicTacToe extends JFrame implements ActionListener {
private final JPanel panel = new JPanel();
private final XOButtons[] buttons = new XOButtons[9];
private int turn = 0;
public TicTacToe() {
setTitle("Tic Tac Toe");
setSize(600, 600);
setLocation(100, 100);
getContentPane().setBackground(Color.CYAN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(new GridLayout(3, 3, 5, 5));
panel.setBackground(Color.BLUE);
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new XOButtons();
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
add(panel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
XOButtons source = (XOButtons) actionEvent.getSource();
if (turn == 0) {
source.toggleX();
setTitle("O Turn");
} else if (turn == 1) {
source.toggleO();
setTitle("X's Turn");
}
turn = (turn + 1) % 2;
}
public static void main(String[] args) {
new TicTacToe();
}
}
class XOButtons extends JButton {
private ImageIcon xIcon = null;
private ImageIcon oIcon = null;
XOButtons() {
try {
xIcon = new ImageIcon(new URL("https://i.stack.imgur.com/in9g1.png"));
oIcon = new ImageIcon(new URL("https://i.stack.imgur.com/wCF8S.png"));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
public void toggleX() {
if (getIcon() == null) {
setIcon(xIcon);
} else {
setIcon(null);
}
}
public void toggleO() {
if (getIcon() == null) {
setIcon(oIcon);
} else {
setIcon(null);
}
}
}

Problem with Java GridLayout and adding Buttons

I want to add 100 buttons into an GridLayout and my code works but sometimes it only adds one button and if I click where the other buttons belong the button where I clicked appears.
it happens totally randomly and I don't get it.
Here is my code:
public class GamePanel extends JPanel {
GameUI controler;
GridLayout gameLayout = new GridLayout(10,10);
JButton gameButtons[] = new JButton[100];
ImageIcon ice;
JButton startButton;
JButton exitButton;
ImageIcon startIcon;
ImageIcon exitIcon;
URL urlIcon;
private int i;
public GamePanel(GameUI controler) {
this.setLayout(gameLayout);
this.controler = controler;
urlIcon = this.getClass().getResource("/icons/Overlay.png");
ice = new ImageIcon(urlIcon);
makeButtons();
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
public void makeButtons() {
for(i = 0; i< 100; i++) {
gameButtons[i] = new JButton(ice);
this.add(gameButtons[i]);
revalidate();
}
repaint();
}
}
update:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.net.URL;
public class GameUI extends JFrame {
ImageIcon i;
Image jFrameBackground;
JButton startButton;
JButton exitButton;
ImageIcon startIcon;
ImageIcon exitIcon;
public GameUI() {
setResizable(false);
this.setSize(1200, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
BackGroundPanel backGroundPanel = new BackGroundPanel();
GamePanel panel = new GamePanel(this);
ButtonPanel buttonPanel = new ButtonPanel();
panel.setSize(500,500);
panel.setLocation(100, 150);
backGroundPanel.setSize(this.getWidth(),this.getHeight());
backGroundPanel.setLocation(0,0);
buttonPanel.setSize(390,50);
buttonPanel.setLocation(100,100);
this.add(backGroundPanel);
this.add(panel);
this.add(buttonPanel);
backGroundPanel.setBackground(Color.BLACK);
}
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
javax.swing.SwingUtilities.invokeAndWait(
new Runnable(){
#Override
public void run() {
GameUI ui = new GameUI();
ui.setVisible(true);
}
}
);
}
}
As I mentioned in comments, you're using a null layout, and this is the source of your problems.
You're using the null layout to try to layer JPanels, one on top of the other, and that is not how it should be used or what it is for, nor how you should create backgrounds. This is having the effect of the background covering your buttons until your mouse hovers over them.
Instead if you wish to create a background image, I would recommend that you:
create a JPanel, say called BackgroundPanel,
override its paintComponent method,
call its super.paintComponent(g); on your method's first line
then draw the image it should display
then give it a decent layout manager
and add your GUI components to it
Make sure that any JPanels added to it are made transparent via .setOpaque(false)
Other options include using a JLayeredPane, but you really don't need this just to have a background.
For example, the following code produces:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GameUI2 {
private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/3/3f/"
+ "Butterfly_Nebula_in_narrow_band_Sulfur%2C_Hydrogen_and_Oxygen_Stephan_Hamel.jpg";
private static final String BTN_IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/5/54/Crystal_Project_Games_kids.png";
private static void createAndShowGui() {
BufferedImage bgImg = null;
BufferedImage btnImg = null;
try {
URL bgImgUrl = new URL(IMG_PATH);
URL btnImgUrl = new URL(BTN_IMG_PATH);
bgImg = ImageIO.read(bgImgUrl);
btnImg = ImageIO.read(btnImgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
BackgroundPanel2 mainPanel = new BackgroundPanel2(bgImg);
mainPanel.setLayout(new GridBagLayout());
GamePanel2 gamePanel = new GamePanel2(btnImg);
mainPanel.add(gamePanel);
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class BackgroundPanel2 extends JPanel {
private Image backgroundImg;
public BackgroundPanel2(Image backgroundImg) {
this.backgroundImg = backgroundImg;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || backgroundImg == null) {
return super.getPreferredSize();
} else {
int w = backgroundImg.getWidth(this);
int h = backgroundImg.getHeight(this);
return new Dimension(w, h);
}
}
}
#SuppressWarnings("serial")
class GamePanel2 extends JPanel {
public static final int MAX_BUTTONS = 100;
private static final int IMG_WIDTH = 40;
JButton[] gameButtons = new JButton[MAX_BUTTONS];
public GamePanel2(Image buttonImg) {
setOpaque(false);
if (buttonImg.getWidth(this) > IMG_WIDTH) {
buttonImg = buttonImg.getScaledInstance(IMG_WIDTH, IMG_WIDTH, Image.SCALE_SMOOTH);
}
Icon icon = new ImageIcon(buttonImg);
setLayout(new GridLayout(10, 10, 4, 4));
for (int i = 0; i < gameButtons.length; i++) {
int finalIndex = i;
JButton btn = new JButton(icon);
btn.addActionListener(e -> {
String text = String.format("Button: %02d", finalIndex);
System.out.println(text);
});
add(btn);
gameButtons[i] = btn;
}
}
}

Java Swing - the best control for specific task

I need to divide java swing window into many fields, something similar to the table or chess board. Color of each cell should be dependent on the object which this cell represents (each object has coordinates, which are changing during the game, so the color of each cell is not constant).
Additionally, if the user clicks on the empty field (white color), then a new random object is created and this object is assigned to these field (and field color is changing).
Which of java swing controls will be the best for these functionalities?
If I were you I would make 2 panel classes(white and black), the white one with a MouseAdapter, so that when one of the panels is clicked you can pull a random JLabel from an array. Here's an example that might help (roughly 120 lines):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class ScratchPaper extends JFrame {
private static final long serialVersionUID = 1L;
private static final int GRIDSIZE = 8;
private JPanel[][] whitePanel = new WhitePanel[GRIDSIZE][GRIDSIZE];
private JPanel[][] blackPanel = new BlackPanel[GRIDSIZE][GRIDSIZE];
private Random rand = new Random();
JButton b1 = new JButton("Btn1");
JButton b2 = new JButton("Btn2");
JButton b3 = new JButton("Btn3");
JLabel l1 = new JLabel("Lbl1");
JLabel l2 = new JLabel("Lbl2");
JLabel l3 = new JLabel("Lbl3");
JPanel panel = new JPanel();
private JComponent[][] randObjects = {{b1, b2, b3}, {l1, l2, l3}, {panel, panel, panel}};
private Color[] randColors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA};
public ScratchPaper() {
initGUI();
setTitle("EXAMPLE");
pack();
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void initGUI() {
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(GRIDSIZE, GRIDSIZE)); // makes 8*8 grid
add(centerPanel, BorderLayout.CENTER);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Component clickedComp = findComponentAt(e.getPoint());
JPanel target = (JPanel) clickedComp;
panel.setBackground(randColors[rand.nextInt(randColors.length)]);
if (target instanceof WhitePanel){
target.add(randObjects[rand.nextInt(randObjects.length)][rand.nextInt(randObjects[0].length)]);
target.updateUI();
}
}
};
addMouseListener(ma);
for (int row=0; row<GRIDSIZE; row++) {
for (int col=0; col<GRIDSIZE; col++) {
whitePanel[row][col] = new WhitePanel(row, col);
blackPanel[row][col] = new BlackPanel(row, col);
if ((row%2 == 0 && col%2 == 0) || ((row+1)%2 == 0 && (col+1)%2 == 0)) {
centerPanel.add(whitePanel[row][col]);
}
else {
centerPanel.add(blackPanel[row][col]);
}
}
}
}
public static void main(String args[]) {
try {
String className = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
} catch (Exception ex) {
System.out.println(ex);
}
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
new ScratchPaper();
}
});
}
class WhitePanel extends JPanel {
private static final int SIZE = 50;
public WhitePanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.WHITE);
}
}
class BlackPanel extends JPanel {
private static final int SIZE = 50;
public BlackPanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.BLACK);
}
}
}
Try running it! It's actually pretty fun!

Having selected JButton from a 2d array perform an action

I have a 2 dimensional array of JButtons, and I would like to be able to have the button that my mouse is over to perform an action, such as change color. How can I do this? Thanks.
Here is how I am creating the buttons:
for(int r = 0;r<10;r++){
for(int c = 0;c<10;c++){
buttonArray[r][c] = new JButton();
}
}
Here is an example using a loop and a MouseAdapter (since you don't need all the methods from MouseListener ) :
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JButtonHighlighter extends JPanel {
public static void main(final String[] args) {
JFrame frame = new JFrame();
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new GridLayout(10, 10));
JButton[][] buttonArray = new JButton[10][10];
for (int r = 0; r < 10; r++) {
for (int c = 0; c < 10; c++) {
final JButton newButton = new JButton();
final Color originalColor = newButton.getBackground();
final Color highlightColor = Color.GREEN;
newButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(final MouseEvent e) {
newButton.setBackground(highlightColor);
}
#Override
public void mouseExited(final MouseEvent e) {
newButton.setBackground(originalColor);
}
});
buttonArray[r][c] = newButton;
contentPanel.add(newButton);
}
}
frame.setContentPane(contentPanel);
frame.setSize(100, 100);
frame.setVisible(true);
}
}

How to solve the error? swing button repaint

I am using the menu to try to change the button number.
But this should not refresh.
How do I solve this?
I want 'file -> modify -> button 10x10 -> 20x20 change. '
To test and modify the source below. Please...
Please give me change the source. TT
package com.test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MineMain extends JFrame {
private GridLayout grid;
private JPanel jp;
private int rownum, colnum;
private JButton[][] btn = null;
public MineMain(){
super("MINE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu_Init();
// grid = new GridLayout();
// jp = new JPanel();
rownum = 10;
colnum = 10;
Init(200, 250);
}
private void setBtn(int row, int col){
btn = new JButton[row][col];
}
public void Init(int w, int h){
if(jp != null)
jp.removeAll();
else
jp = null;
btn = null;
jp = null;
// jp.removeAll();
grid = new GridLayout(rownum, colnum, 0, 0);
jp = new JPanel(grid);
setBtn(rownum, colnum);
for(int i=0;i<btn.length;i++){
for(int j=0;j<btn[i].length;j++){
btn[i][j] = new JButton();
jp.add(btn[i][j]);
}
}
// jp.revalidate();
// jp.repaint();
this.add(jp);
this.setSize(w, h);
this.setLocation(200, 200);
this.setVisible(true);
this.setResizable(false);
}
public void Menu_Init(){
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
JMenu filemenu = new JMenu("File(F)");
filemenu.setMnemonic('F');
JMenuItem startmenu = new JMenuItem("New Game(N)");
startmenu.setMnemonic('N');
startmenu.setActionCommand("NEW START");
startmenu.addActionListener(new MenuActionListener());
filemenu.add(startmenu);
JMenuItem minecntmenu = new JMenuItem("MINE MODIFY(M)");
minecntmenu.setMnemonic('M');
minecntmenu.setActionCommand("MODIFY");
minecntmenu.addActionListener(new MenuActionListener());
filemenu.add(minecntmenu);
JMenuItem close = new JMenuItem("CLOSE(C)");
close.setMnemonic('C');
filemenu.add(close);
bar.add(filemenu); //JMenuBar에 JMenu 부착
}
private class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("START")){
JOptionPane.showMessageDialog(null, "NEW GAME", "MINE", JOptionPane.YES_NO_OPTION);
} else if(e.getActionCommand().equals("MODIFY")){
modify(2);
}
}
}
private void modify(int lvl){
rownum = 20;
colnum = 20;
Init(400, 500);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MineMain();
}
}
I see you are calling Init() again on modify().
Within Init(), I am assuming you are using
if(jp != null)
jp.removeAll();
else
jp = null;
to clear out the JPanel?
You want to remove the existing JPanel (i.e. jp) from the JFrame (i.e. this) before continuing at this point.
So, you could change your code to
if(jp != null) {
// JPanel already exists. so, remove JPanel jp from the JFrame
this.remove(jp);
jp.removeAll();
} else
jp = null;

Categories

Resources