Java-Graphics(画图类)
就比如画一个矩形,你给出矩形左上角坐标,再给出矩形长度和宽度就可以在JFrame上画出来一个矩形
除了矩形之外,还可以画椭圆、圆、圆弧、线段、多边形、图像等
下面给出画矩形的代码
Rect.java
importjava.awt.Color;importjava.awt.Graphics;importjavax.swing.JPanel;public class Rect extendsJPanel{public static Color myColor =Color.RED;public static int myX = 10;public static int myY = 10;public static int myWidth = 100;public static int myHeight = 100;
@Overridepublic voidpaintComponent(Graphics g) {super.paintComponent(g);
g.setColor(myColor);
g.fillRect(myX+100,myY+100,myWidth,myHeight); //画矩形着色块
g.drawRect(myX,myY,myWidth,myHeight); //画矩形线框
}
}
Main.java
importjava.awt.Color;importjavax.swing.JFrame;public classMain{//Note how we don't need to extend the Rect class (It just adds confusion)
public static voidmain(String[] args ) {
JFrame window= new JFrame("test");
window.setSize(1000, 800);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//create Rect
Rect rect = newRect();//set the size of the new panel//rect.setPreferredSize(new Dimension(800, 600));//add the rect to your JFrame
window.add(rect);//如果你改变了Rect的静态属性color的值,它会同步更新,你把下面的代码注释了还可以画出矩形,那样的话画出来的图形就是红色的
Rect.myColor =Color.BLUE;
Rect.myX= 400;
Rect.myY= 400;//加上下面,但是感觉加不加没啥差距,,学废了,,,,
rect.repaint();
}