- Java 编程示例
- 示例 - 首页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小应用程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- 有用的 Java 资源
- Java - 快速指南
- Java - 有用资源
如何使用 Java 在框架中显示颜色
问题说明
如何在框架中显示颜色?
解决方案
以下示例展示如何使用 image 类的 setRGB 方法在框架中显示所有颜色。
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Main extends JComponent {
BufferedImage image;
public void initialize() {
int width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int index = 0;
for (int i = 0; i < height; i++) {
int red = (i * 255) / (height - 1);
for (int j = 0; j < width; j++) {
int green = (j * 255) / (width - 1);
int blue = 128;
data[index++] = (red<<16) | (green<<8) | blue;
}
}
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
}
public void paint(Graphics g) {
if (image == null)
initialize();
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
JFrame f = new JFrame("Display Colours");
f.getContentPane().add(new Main());
f.setSize(300, 300);
f.setLocation(100, 100);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
结果
上面的代码示例将生成以下结果。
Displays all the colours in a frame.
以下是在框架中显示颜色的示例。
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Panel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
displayJFrame();
}
});
}
static void displayJFrame() {
JFrame frame = new JFrame("Tutorialspoint");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.red);
frame.setPreferredSize(new Dimension(400, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
java_simple_gui.htm
广告