public JPanel getDraw(){
return new NewPanel();
}
static class NewPanel extends JPanel{
protected void paintComponent(Graphics g){

super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(20, 20, 50, 50);
g.drawLine(0, 0,100 , 500);
g.drawString("Banner", 0, 40);
}
}
这是一个类中的一部分,借助getDraw()函数返回画图的panel的时候只会有一条线即drawline,为什么?

解决方案 »

  1.   

    貌似我的运行结果是正常的import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class TestFrame extends JFrame
    {
    public TestFrame()
    {
    this.setLayout(new GridLayout(1, 2));
    add(getDraw());
    add(getDraw());
    }

    public JPanel getDraw()
    {
    return new NewPanel();
    } static class NewPanel extends JPanel
    {
    protected void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.drawRect(20, 20, 50, 50);
    g.drawLine(0, 0,100 , 500);
    g.drawString("Banner", 0, 40);
    }
    }

    public static void main(String[] args)
    {
    JFrame frame = new TestFrame();
    frame.setSize(400, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }
      

  2.   

    找到了解决问题的办法,但是任然不懂,我以前是这个样子的:
    public class DeMain extends JFrame{

    private CurveAnalysis curve=new CurveAnalysis();
    private JPanel draw=new JPanel();
    public DeMain(){
    draw.add(curve.getDraw());
    add(draw);
    }

        
    public static void main(String []args){
    DeMain frame=new DeMain();
    frame.setTitle("Records");
    frame.setSize(650,600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }}
    先新建一个JPanel draw,再加入到框架中,这样的话就不行,不用那个JPANEL就可以,为什么?