案例代码:
import javax.swing.*;
import java.awt.*;
public class DrawOnJPanel extends JPanel{
public static void main(String[] args) {
JFrame f=new JFrame("绘制图形");
DrawOnJPanel d=new DrawOnJPanel();
f.getContentPane().add(d);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,200);
f.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawString("字符串",20,50);
g.drawLine( 120,10,200,50);
g.drawRect(60,80,getWidth()/2-30,getHeight()/2-30);
g.drawOval(60,80,getWidth()/2-30,getHeight()/2-30);
}
}
案例运行图: