在Java的GUI编程中,如何使用GUI绘制一个实心的矩形?
以下示例演示如何使用Graphics
类的fillRect()
方法显示一个实心矩形。
package com.yiibai;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SolidRectangle extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setTitle("实心的矩形");
f.setSize(400, 400);
f.add(new SolidRectangle());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
g.fillRect(5, 15, 150, 175);
}
}
上述代码示例将产生以下结果。
示例-2
以下是使用GUI绘制实心矩形的另一个示例。
package com.yiibai;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SolidRectangle2 extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(31, 21, 1));
g2d.fillRect(250, 195, 90, 60);
}
public static void main(String[] args) {
SolidRectangle2 rects = new SolidRectangle2();
JFrame frame = new JFrame("绘制实心矩形");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(rects);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
上述代码示例将产生以下结果。