import java.awt.*;import javax.swing.*;import java.awt.event.*;public class cut extends JFrame{ static JPanel panel = new JPanel(); static JButton but1 = new JButton("draw 圆"); static JButton but2 = new JButton("draw 椭圆"); static int circle = 0; public cut() { setBounds(300, 200, 350, 370); setLayout(new BorderLayout()); add(panel); panel.setLayout(new FlowLayout()); panel.add(but1); panel.add(but2); setDefaultCloseOperation(3);// Graphics g = getGraphics();// paint(g); setVisible(true); } public void paint(Graphics g) { g.drawString("花园或椭圆", 80, 80); g.drawOval(70, 160, 70, 70); g.drawOval(150, 160, 70, 90); } public static void main(String[] args) { new cut(); }}看了书上例子后我有很多不解,比如:1、我把那两句注释了,没有了g,为什么paint函数不会报错,照样运行?2、打开那两句后提示3处指针异常?3、提示一个区别paint,repaint,update的例子谢谢
paint方法不报错,实际原因是你Cut继承JFrame类,这个paint方法实际上是重写了paint方法,没有语法错误自然一切正常。
打开两句之后提示的指针异常是因为getGraphics()方法返回对象为null,然后你再调用paint方法的null对象的方法就报错最后一个问题无法一两句话说清楚,repaint是UI图形有变化之后的重绘组件方法,paint是普通的绘图组件,这两者的功能设计目的不一样,update也是UI图形有变化后的重绘方法你上面程序的paint重写是有问题的,需要添加一行命令
package csdn;import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Cut extends JFrame{ static JPanel panel = new JPanel(); static JButton but1 = new JButton("draw 圆"); static JButton but2 = new JButton("draw 椭圆"); static int circle = 0; public Cut() { setBounds(300, 200, 350, 370); setLayout(new BorderLayout()); add(panel); panel.setLayout(new FlowLayout()); panel.add(but1); panel.add(but2); setDefaultCloseOperation(3);// Graphics g = getGraphics();
//
// paint(g); setVisible(true); } public void paint(Graphics g) {
super.paint(g);
g.drawString("花园或椭圆", 80, 80); g.drawOval(70, 160, 70, 70); g.drawOval(150, 160, 70, 90); } public static void main(String[] args) { new Cut(); }}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;public class App14_2//没有继承框架类
{
static JFrame frm = new JFrame();
static JPanel panel = new JPanel();
int circle = 0;
public App14_2()
{
frm.setBounds(300, 200, 350, 370);
frm.setLayout(new BorderLayout());
frm.add(panel);
panel.setLayout(new FlowLayout());
frm.setDefaultCloseOperation(3);
frm.setVisible(true);
Graphics g = frm.getGraphics();//试图获取绘图区域
paint(g);//传递绘图区域
}
public void paint(Graphics g)
{
g.drawString("花园或椭圆", 120, 250);
g.drawOval(70, 160, 70, 70);
g.drawOval(150, 220, 70, 120);
}
public static void main(String[] args)
{
new App14_2();
}
}