java - 如何更改 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);
}
}
任何建议都非常感谢。
解决方案
而不是创建一个新类,您可以将动作侦听器添加到您的按钮,如下所示
playButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
//do stuff onclick
frame.getContentPane().setBackground(Color.yellow);
}
});
推荐阅读
- javascript - 使用 ASP.NET Razor 的 Ajax POST
- android - 如何在 RecyclerView 上使用 Firebase 存储显示多个用户的图像
- java - 接收数据时如何以图形方式更改数字?
- python - .map_diag(plt.hist,bins=30) - 对角线上没有直方图
- c# - 单击关闭按钮后,我在这一行出现 System.IO.IO.Exception 错误 'string machine_data = serialPort1.ReadTo("\u0003");'
- laravel - Laravel Echo + Websockets + 私人频道
- css - 如何使用 Bootstrap 4 和 Scss 将容器的宽度覆盖为 1440px 并使列同时响应
- android - 在 RecyclerView android 中使用 MediaPlayer 设置 ProgressBar
- c# - File.WriteAllLines 在 C# 中不起作用(Visual Studio 19)
- tfs - 如何在 TFS 2015 中创建一个文件夹来存储构建定义?