gpt4 book ai didi

java - 如何更改 Play 类中的背景颜色?

转载 作者:行者123 更新时间:2023-12-02 10:26:32 26 4
gpt4 key购买 nike

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

非常感谢任何建议。

最佳答案

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

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

关于java - 如何更改 Play 类中的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com