下面的代码做一个输出图形的示例:
下面的代码需要注意的地方:
g是个什么呢?g是特定平台的抽象Graphics类的具体子类的实例。
那个Graphics类封装了平台的细节,可以再不考虑特定平台的情况下绘图。
super.paintComponent(g); 是为了确保视图区域在显示新的图之前被清除
repaint();是Component类里面的方法,可以请求再次的显示组件。调用他的时候会让JVM调用paintComponent
绘图一般是在JPanel上面的,所以一般是扩展JPanel,在自己的扩展类里面加入想加入的东西
package graph;
import java.awt.*;
import javax.swing.*;
public class FigurePanel extends JPanel{
public static final int LINE=1; //去一个常数的序号
public static final int RECTANGLE=2;
public static final int ROUND_RECTANGLE=3;
public static final int OVAL=4;
private int type=1; //默认直线和不填充
private boolean filled=false;
public FigurePanel() { //几个构造方法
}
public FigurePanel(int type) {
this.type=type;
}
public FigurePanel(int type,boolean filled) {
this.type=type;
this.filled=filled;
}
protected void paintComponent(Graphics g) { //画图的类
super.paintComponent(g);
int width=getWidth();
int height=getHeight();
switch(type) { //判断是哪种形状
case LINE:
g.setColor(Color.BLACK);
g.drawLine(10, 10,width-10 ,height-10); //画了两条线
g.drawLine(width-10, 10,10 ,height-10);
break;
case RECTANGLE:
g.setColor(Color.BLUE);
if(filled)
g.fillRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(0.8*height));
else
g.drawRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(0.8*height));
break;
case ROUND_RECTANGLE:
g.setColor(Color.RED);
if(filled)
g.fillRoundRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),
(int)(0.8*height),20,20);
else
g.drawRoundRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),
(int)(0.8*height),20,20);
break;
case OVAL:
g.setColor(Color.BLACK);
if(filled)
g.fillOval((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),
(int)(0.8*height));
else
g.drawOval((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),
(int)(0.8*height));
break;
}
}
public void setType(int type) {
this.type=type;
repaint(); //刷新视图
}
public int getType() {
return type;
}
public void setFilled(boolean filled) {
this.filled=filled;
repaint();
}
public boolean isFilled() {
return filled;
}
public Dimension getPreferredSize() { //覆盖component类的getpreferredsize方法,确定尺寸
return new Dimension(80,80);
}
}
package graph;
import java.awt.*;
import javax.swing.*;
public class TestFigurePanel extends JFrame{
public TestFigurePanel() {
setLayout(new GridLayout(2,3,5,5)); //网格布局
add(new FigurePanel(FigurePanel.LINE));
add(new FigurePanel(FigurePanel.RECTANGLE));
add(new FigurePanel(FigurePanel.ROUND_RECTANGLE));
add(new FigurePanel(FigurePanel.OVAL));
add(new FigurePanel(FigurePanel.RECTANGLE,true));
add(new FigurePanel(FigurePanel.ROUND_RECTANGLE,true));
}
public static void main(String[] args) {
TestFigurePanel frame=new TestFigurePanel();
frame.setTitle("TestFigurePanel");
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}