如何设置java中窗口的前景色和背景色
时间: 2023-06-19 21:10:51 浏览: 83
在Java中,可以使用`setBackground(Color color)`和`setForeground(Color color)`方法分别设置窗口的背景色和前景色。具体步骤如下:
1. 创建一个窗口对象,例如`JFrame frame = new JFrame("Example");`
2. 获取窗口内容面板,例如`Container contentPane = frame.getContentPane();`
3. 设置背景色,例如`contentPane.setBackground(Color.WHITE);`
4. 设置前景色,例如`contentPane.setForeground(Color.BLACK);`
5. 最后,显示窗口,例如`frame.setVisible(true);`
完整示例代码如下:
```java
import javax.swing.*;
import java.awt.*;
public class Example {
public static void main(String[] args) {
JFrame frame = new JFrame("Example");
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setForeground(Color.BLACK);
frame.setVisible(true);
}
}
```