Как передать значение переменной из одного экземпляра класса JPanel в другой?

Существует несколько панелей JPanel которые меняют друг друга. На первой существует чекбокс для определения цвета игровой панели, которая включается после старта игры.

Как установить значение setBackground(Color.YELLOW); из одной панели для другой?

Панель управления и старта:

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;

    import javax.swing.AbstractAction;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.Border;

public class Home_panel extends JPanel {
    private static final long serialVersionUID = 1L;
    public static final Color String = null;
    private Main main;
    
    protected Game game;
    protected Image img;
    private JButton play;
    private JButton exit;
    private JLabel BGColor;
    private JLabel gameLevel;
    JCheckBox checkbox_BColor_Black;
    private JCheckBox checkbox_level_1;
    private JCheckBox checkbox_level_2;
    private JCheckBox checkbox_level_3;
    private JCheckBox checkbox_BColor_yell;
     
    
    Home_panel() throws IOException {

        setBounds(0, 0, Main.WIDTH, Main.HEIGTH);
        setLayout(null); // отключаем менеджер компоновки
        setFocusable(true);
        
        
        
        play = new JButton();
        play.setOpaque(false);
        play.setContentAreaFilled(false);
        play.setBorderPainted(false);
        play.setIcon(Resources.ICON_PLAY);
        play.setBounds((getWidth()-900) / 9, (getHeight() + 10) / 6, 390, 120);
        play.setRolloverEnabled(false); // отключение эффетка подсветки при наведении
        Border no_border = BorderFactory.createEmptyBorder(); // убираем синие границы картинки
        play.setBorder(no_border);
        add(play);

        exit = new JButton();
        exit.setOpaque(false);
        exit.setContentAreaFilled(false);
        exit.setBorderPainted(false);
        exit.setBounds((getWidth()) / 2, (getHeight() + 10) / 6,  390, 120);
        exit.setRolloverEnabled(false);
        exit.setBorder(no_border);
        exit.setIcon(Resources.ICON_EXIT);
        add(exit);

        BGColor = new JLabel("Цвет фона: ");
//      setBackground(Color.white);
        BGColor.setBounds((getWidth() - 200) / 9, (getHeight() + 700) / 5, 90, 50);
        BGColor.setBorder(no_border);
        add(BGColor);

        gameLevel = new JLabel("Уровень сложности: ");
//      setBackground(Color.white);
        gameLevel.setBounds((getWidth() - 200) / 8, (getHeight() + 700) / 3, 140, 50);
        gameLevel.setBorder(no_border);
        add(gameLevel);

        
        checkbox_BColor_Black = new JCheckBox(new CheckboxAction("Черный"));
        checkbox_BColor_Black.setOpaque(false);
        checkbox_BColor_Black.setBounds((getWidth()) / 5, (getHeight() + 700) / 5, 90, 50);
        checkbox_BColor_Black.setBorder(no_border);

        checkbox_BColor_yell = new JCheckBox(new CheckboxAction("Желтый"));

        checkbox_BColor_yell.setOpaque(false);
        checkbox_BColor_yell.setBounds((getWidth()) / 5, (getHeight() + 880) / 5, 90, 50);
        checkbox_BColor_yell.setBorder(no_border);

        checkbox_level_1 = new JCheckBox("Уровень 1");
        checkbox_level_1.setOpaque(false);
        checkbox_level_1.setBounds((getWidth()-100) / 3, (getHeight() + 235) / 2, 90, 50);
        checkbox_level_1.setBorder(no_border);

        checkbox_level_2 = new JCheckBox("Уровень 2");
        checkbox_level_2.setOpaque(false);
        checkbox_level_2.setBounds((getWidth()-100) / 3, (getHeight() + 285) / 2, 90, 50);
        checkbox_level_2.setBorder(no_border);

        checkbox_level_3 = new JCheckBox("Уровень 3");
        checkbox_level_3.setOpaque(false);
        checkbox_level_3.setBounds((getWidth()-100) / 3, (getHeight() + 330) / 2, 90, 50);
        checkbox_level_3.setBorder(no_border);

        add(checkbox_BColor_Black);
        add(checkbox_BColor_yell);
        add(checkbox_level_1);
        add(checkbox_level_2);
        add(checkbox_level_3);

        play.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {
                play.setIcon(Resources.ICON_PLAY);
            }
        });

        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        exit.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {
                exit.setIcon(Resources.ICON_EXIT);
            }
        });

    }

    public JButton getPlayButton() {
        return play;
    }
    
    
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(Resources.BACKROUND, 0, 0, getWidth(), getHeight(), null);
        String message = "Добро пожаловать в игру змейка!";
        g.setFont(new Font("Minicomputer Light 300", Font.CENTER_BASELINE, 28));
        int message_wight = g.getFontMetrics().stringWidth(message); // ширина текста
        g.drawString(message, (getWidth() - message_wight) / 2, (getHeight() - 100) / 7); // по середине
        
        }
    }


од


Панель Игры:

   
import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import java.io.IOException;


public class Game extends JPanel implements ActionListener  {
    private static final long serialVersionUID = 1L;
    private Main main;
    final int SNAKE_SIZE = 10;
    final int APPLE_SIZE = 10;
    final int OBSTACLE_SIZE = 10;
    public int score;

    private boolean game;
    protected Game gm;
    private List<Point> snake = new ArrayList<Point>();
    private List<Point> apples = new ArrayList<Point>();
    private List<Point> obstacles = new ArrayList<Point>();
    private Random rng = new Random();
    private Direction direction = Direction.DOWN; // начальное направление движения змейки вправо
    public Timer timer;
    public int  speed = 100;
    private int r = 0;
    public int round = 12;
    protected Color green_color = Color.green;
    protected Color red_color = Color.red;
    protected Color white_color = Color.white;
    protected Color brown_color = new Color(165, 42, 42);
    protected Color black_color = Color.black;
 
    
    Game(Main main) throws IOException {
        this.main = main;
        setBounds(68,57, Main.WIDTH - 130, Main.HEIGTH - 130);
        setLayout(null);
        setBackground(Color.BLACK);
        addKeyListener(new Controller(this, main));
        setFocusable(true);
        start(speed);
        
    }

    
    
    void start(int speed){
        game = true;
        score = 0;
        
        // длинна змеи
        snake.add(new Point(2, 0));
        snake.add(new Point(1, 0));
        snake.add(new Point(0, 0));
        newApple();
        newObstacle();
        timer = new Timer(speed, this);
        timer.start();
    }

    void newApple() {
        while (true) { 
            Point apple = new Point(rng.nextInt(getWidth() / APPLE_SIZE), rng.nextInt(getHeight() / APPLE_SIZE));
            if (!apples.contains(apple) && !snake.contains(apple)) { // если яблока с такими координатами нет и не на
                                                                        // змее
                apples.add(apple);
                break;
            }
        }
    }
    
    void newObstacle() {
        for(r=0; r< round; r++) {
        while (true) { 
            Point obstacle = new Point(rng.nextInt(getWidth() / OBSTACLE_SIZE), rng.nextInt(getHeight() / OBSTACLE_SIZE));
            if (!obstacles.contains(obstacle) && !snake.contains(obstacle) && !apples.contains(obstacle)) { 
                obstacles.add(obstacle);
                break;
            }
        }
    }
    }
    void snake_move() throws IOException {
        
        Point head = snake.get(0);
        int dx = head.x, dy = head.y;
        switch (direction) {
        case UP:
            dy -= 1;
            break;
        case DOWN:
            dy += 1;
            break;
        case RIGHT:
            dx += 1;
            break;
        case LEFT:
            dx -= 1;
            break;

        }
        
        Point newHead = new Point(dx, dy);
        snake.add(0, newHead);
        
        // если вышел за границу
        if (newHead.x < 0 || newHead.y < 0 || newHead.x >= getWidth() / SNAKE_SIZE
                || newHead.y >= getHeight() / SNAKE_SIZE) {
            game = false;
            return;
        }
        // если врезался в себя
        if (snake.subList(1, snake.size()).contains(newHead)) {
            game = false;
            return;
        }
        // если яблоко увлечиваем счетчик
        if (apples.contains(newHead)) {
            score++;
            
            apples.remove(newHead);
            main.update_score(score); // вывод счетчика
            //if(score==+1) round=+8;
            newApple();
            newObstacle();
            //if(speed!=0) start(speed=speed-10);
        } else
            snake.remove(snake.size() - 1);
        
        if (obstacles.contains(newHead)) {
            //game = false;
            return;
         }
    }

    void setDirection(Direction direction) {
        // запрещает изменение направления, если игра закончена
        if (!game) {
            return;
        }
        // запрещает изменение направления на противоположное
        if (this.direction == Direction.UP && direction == Direction.DOWN
                || this.direction == Direction.DOWN && direction == Direction.UP
                || this.direction == Direction.LEFT && direction == Direction.RIGHT
                || this.direction == Direction.RIGHT && direction == Direction.LEFT) {
            return;
        }
        this.direction = direction;
    }

    @Override
    protected void paintComponent(Graphics g) { // рисования графики внутри компонента
        super.paintComponent(g); // настройка графического контекста
       
        //Конец игры
        if (!game) {
            main.game_over_start();
            return;
        }
        
        //Змея
        g.setColor(green_color);
        for (Point point : snake) {
            g.fillOval(point.x * SNAKE_SIZE, point.y * SNAKE_SIZE, SNAKE_SIZE, SNAKE_SIZE); // отрисовка

        }
        
        //Яблоко
        g.setColor(red_color);
        for (Point point : apples) {
            g.fillOval(point.x * APPLE_SIZE, point.y * APPLE_SIZE, APPLE_SIZE, APPLE_SIZE);
        }
        
        //Препятствие
        g.setColor(green_color);    
        for (Point point : obstacles) {
            g.fillOval(point.x * OBSTACLE_SIZE, point.y * OBSTACLE_SIZE, OBSTACLE_SIZE, OBSTACLE_SIZE);
        }
        
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            snake_move();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        repaint();
    }


    public int setSpeed(int speed){
        return this.speed=speed;
    }


}

Ответы (1 шт):

Автор решения: Владимир
public void startGame() throws IOException {
    game = new Game(this);
    home.setVisible(false);
    
    this.add(game); // добавляем игру
    if (home.checkbox_BColor_Black.isSelected()) {
        game.setBackground(Color.BLACK);    
        System.out.println("Color is black");
        repaint(); 
    } else  repaint(); 
    if (home.checkbox_BColor_yell.isSelected()) {
        this.game.setBackground(Color.yellow);  
         System.out.println("Color is yellow");
        repaint(); 
    } else { 
        repaint(); 
    } 
    game.requestFocus(); // фокусируем игру
    revalidate(); // обновления компоновки (пересчитает размер и расположение компонентов)
    repaint(); // обновления отрисовки компонентов
}
→ Ссылка