首先请看代码:package Test_Rectangle2D;import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;import javax.swing.JFrame;public class cla_Rectangle2D 
{
public static void main(String[] args) 
{
EventQueue.invokeLater(new Runnable() {
public void run() 
{
DrawFrame frame = new DrawFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
private static class Coord_And_Size
{
/**
 * 矩形坐标:左上角坐标
 */
int r_pos_x ;
int r_pos_y ;
/**
 * 矩形大小:长、宽
 */
int r_size_width ;
int r_size_height ;
};
private static Coord_And_Size aim = new Coord_And_Size();
/**
 * 设置默认图形坐标和长宽比例
 */
private void DefaultCoordAndSize()
{
aim.r_pos_x = 100 ;
aim.r_pos_y = 100 ;
aim.r_size_height = 250 ;
aim.r_size_width = 250 ;
}
/**
 * 内容窗格容器对象
 */
Container con = this.getContentPane();

public DrawFrame() 
{
DefaultCoordAndSize();
        //      以下这句没用,是我出问题后抱着试试的态度写的,这句可以删去
// con.paintComponents(getGraphics());
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
Graphics2D g2 = (Graphics2D)g ;
Rectangle2D rect = new Rectangle2D.Double(
aim.r_pos_x, aim.r_pos_y, aim.r_size_width, aim.r_size_height);
g2.draw(rect);
}
}
一般人直接在窗格组件里面重写paintComponent(g);然后把窗格组件放到框架的内容窗格里。我这一次直接在框架里面覆写paintComponent(g),结果代码显示不出我的“矩形”。我想请问各位大神,错在何处,怎么直接改?
【特别说明:我并不打算在组件里写好paintComponent(),再把组件放入框架的内容窗格中】请教,谢谢!!!

解决方案 »

  1.   


    首先要说的是:我override错了!应该是 public void paintComponents(Graphics g),我少了个 's' ,
    但即便改过来了,还是不行,求教!我想了很久,没通!!! 
      

  2.   


    现在重写好了!!!
    突然发现,没有调用paintComponents()
    @Override
    public void paintComponents()
    {
       ...
    }
    于是我在main函数里面paintComponents(frame.getGraphics());
    ,然后就爆出了NullPointException!why?
    求教!!!
      

  3.   

    画图不要在JFrame里画,而是在JPanel里画,然后把JPanel添加到JFrame
      

  4.   


    的确,我见过的所有画图都在JPanel上 。 但我的确想在JFrame上绘制!
    于是写了上面这个代码。不是转牛角尖,而是想通过编程更了解swing 。请问,我怎么样改才能显示在JFrame中 ?