【发布时间】:2023-01-15 09:38:00
【问题描述】:
我正在制作一个制作窗口的程序,在窗口中打印一个十六进制代码,然后制作一个按钮。我想做的是将背景设置为十六进制代码颜色,并使按钮在按下时更改背景。这是我的代码:
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
class Main{
/**
* @param args
*/
public static void main(String[] args){
Random obj = new Random();
int rand_num = obj.nextInt(0xffffff + 1);
String colorCode = String.format("#%06x", rand_num);
JFrame frame = new JFrame();
JLabel textLabel = new JLabel();
JButton button1 = new JButton("New Color");
frame.setTitle("Color Generator");
frame.setSize(500, 500);
//add a method to have colorCode become the background color
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
textLabel.setText(colorCode);
textLabel.setFont(new Font("Veranda", Font.PLAIN, 40));
frame.add(textLabel);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getRootPane().setDefaultButton(button1);
frame.add(button1);
}
}
【问题讨论】:
-
java中有很多gui框架。我建议在您的问题中添加 swing 标签
-
欢迎来到堆栈溢出。请使用 tour 了解 Stack Overflow 的工作原理,并阅读 How to Ask 了解如何提高问题的质量。请显示您尝试过的尝试以及您从尝试中得到的问题/错误消息。
-
单击按钮时,您希望代码的哪一部分更新背景颜色?
标签: java