import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw {
public static void main(String args[])
{
new ChuangKou().CreateJFrame("圓形");
}
}
class DrawPanel extends JPanel
{
public void Draw(Graphics g)
{
super.paint(g);
g.drawOval(50, 50, 60, 60);
g.setColor(Color.BLUE);
}
}
class ChuangKou extends JFrame
{
public void CreateJFrame(String name)
{
JFrame jf=new JFrame(name);
Container container=jf.getContentPane();
jf.setSize(400,400);
jf.setVisible(true);
DrawPanel a=new DrawPanel();
a.setBackground(Color.orange);
setContentPane(a);
jf.add(a);
jf.setBackground(Color.green);
}
}
DrawPanel類需要重寫paint方法,而不是在DrawPanel類的構造函數中寫那些重繪制代碼。
修正DrawPanel類代碼如下,(去掉構造函數,重寫paint方法將構造函數中的代碼放入paint方法中)。
class DrawPanel extends JPanel {
public void Draw(Graphics g) {
}
public void paint(Graphics g) {
super.paint(g);
g.drawOval(50, 50, 60, 60);
g.setColor(Color.BLUE);
}
}
測試,OK。