日期:2014-05-20  浏览次数:20754 次

一个很菜的窗口打印问题
错误点我加了注释,谁能给个合理的解释?我查了API.没搞明白有什么区别...
package   chapter6;
import   javax.swing.*;
import   java.awt.*;

class   NotHelloWorldPanel   extends   JPanel{
private   static   final   int   Message_x=75;
private   static   final   int   Message_y=100;
public   void   paintComponent(Graphics   g){
super.paintComponents(g);//本来这里不可以执行,报错.我加个s就能执行了.
g.drawString( "abc ",   Message_x,   Message_y);

}

}


class   NotHelloWorldFrame   extends   JFrame{
private   static   final   int   DEFAULT_WIDTH=300;
private   static   final   int   DEFAULT_HIGHT=200;

public   NotHelloWorldFrame(){
setTitle( "NotHelloWorld ");
setSize(DEFAULT_WIDTH,DEFAULT_HIGHT);

NotHelloWorldPanel   panel=new   NotHelloWorldPanel();

getContentPane().add(panel);
}
}

public   class   NotHelloWorld{
public   static   void   main(String[]   args){
NotHelloWorldFrame   frame=new   NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

------解决方案--------------------
加个s也是JPanel的一个方法,作用是绘制JPanel上的每个组件.
------解决方案--------------------
其实都是一样的阿,paintcomponents是container的方法,另一个是JComponent的方法,而container是component的子类。
public void paintComponents(Graphics g) {
if (isShowing()) {
GraphicsCallback.PaintAllCallback.getInstance().
runComponents(component, g, GraphicsCallback.TWO_PASSES);
}
}
protected void paintComponent(Graphics g) {
if (ui != null) {
Graphics scratchGraphics = (g == null) ? null : g.create();
try {
ui.update(scratchGraphics, this);
}
finally {
scratchGraphics.dispose();
}
}
}