Как изменить цвет фона в классе Play? - PullRequest
0 голосов
/ 24 декабря 2018

Я хочу изменить цвет фона и очистить окно, не создавая новый JFrame.Какие-либо предложения?

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Dodge EM");
        frame.setSize(1000, 700);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        placeComponents(frame);
        frame.setVisible(true);
        frame.getContentPane().setBackground(Color.black);

    }

    private static void placeComponents(JFrame frame) {
        frame.setLayout(null);

        JLabel dodgeEM = new JLabel("Dodge EM");
        dodgeEM.setForeground (Color.RED);
        dodgeEM.setFont(new Font("Serif", Font.BOLD, 30));
        dodgeEM.setBounds(440,10,300,150);
        frame.add(dodgeEM);


        JButton playButton = new JButton("Play");
        playButton.setBounds(460,150,95,30);
        frame.add(playButton);

        ActionListener play = new Play();
        playButton.addActionListener(play);

        JButton scoresButton = new JButton("Scores");
        scoresButton.setBounds(460,250,95,30);
        frame.add(scoresButton);

        JButton helpButton = new JButton("Help");
        helpButton.setBounds(460,350,95,30);
        frame.add(helpButton);

        JButton quitButton = new JButton("Quit");
        quitButton.setBounds(460,450,95,30);
        frame.add(quitButton);

    }
}

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Play extends JFrame implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        //JOptionPane.showMessageDialog(null, "Play button has been pressed");
        this.getContentPane().setBackground(Color.red);
    }
}

Любые предложения приветствуются.

1 Ответ

0 голосов
/ 24 декабря 2018

Вместо того, чтобы создавать новый класс, вы можете добавить слушателя действия к вашей кнопке, как показано ниже

      playButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            //do stuff onclick
            frame.getContentPane().setBackground(Color.yellow);
        }
    }); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...