I am trying to change the color of mainPanel from a different class. I have a Menu to select a radio button(black background or blue background) that is supposed to change the color of my mainPanel however, I am newer to Java and I have no idea what I am doing wrong. The code is below:
import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; public class MainBoard extends JFrame{ private JPanel mainPanel; public static void main(String[] args) { MainBoard mb = new MainBoard(); mb.setVisible(true); mb.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public MainBoard() { setTitle("Tic-Tac-Toe"); setSize(600,600); mainPanel = new JPanel(new BorderLayout()); mainPanel.setBackground(Color.BLACK); add(mainPanel); Menu menu = new Menu(); setJMenuBar(menu.getMenu()); } public JPanel getMainPanel() { return mainPanel; } public void setMainPanel(Color c) { this.mainPanel.setBackground(c); } }
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class Menu extends JMenu{ private JMenuBar menu; private JMenu file; private JMenu editGUI; private JMenuItem newGame; private JRadioButtonMenuItem blackBackground; private JRadioButtonMenuItem blueBackground; private JMenuItem exit; public Menu() { menu = new JMenuBar(); file = new JMenu("File"); exit = new JMenuItem("Exit"); newGame = new JMenuItem("New Game"); menu.add(file); file.add(newGame); file.add(exit); editGUI = new JMenu("Edit GUI"); ButtonGroup bg = new ButtonGroup(); blackBackground = new JRadioButtonMenuItem("Black Background",false); blueBackground = new JRadioButtonMenuItem("Blue Background",false); bg.add(blueBackground); bg.add(blackBackground); menu.add(editGUI); editGUI.add(blackBackground); editGUI.add(blueBackground); MenuHandler mh = new MenuHandler(); exit.addActionListener(mh); blueBackground.addActionListener(mh); } public JMenuBar getMenu() { return this.menu; } private class MenuHandler implements ActionListener { public void actionPerformed(ActionEvent e){ if(e.getSource() == exit) { System.exit(0); }else if(e.getSource() == blueBackground) { MainBoard mb = new MainBoard(); mb.setMainPanel(Color.BLUE); } } } }
The exit menu item will work, but the blueBackground menu item will not. Thank you for any help!