首页 > 解决方案 > 如何更改 Play 类中的背景颜色?

问题描述

我想更改背景的颜色和一个清晰的窗口而不创建新的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);
    }
}

任何建议都非常感谢。

标签: javaswing

解决方案


而不是创建一个新类,您可以将动作侦听器添加到您的按钮,如下所示

      playButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            //do stuff onclick
            frame.getContentPane().setBackground(Color.yellow);
        }
    }); 

推荐阅读