user1612078
user1612078

Reputation: 585

Not able to see the graphics stuff inside paint() method

I'm doing all Graphics stuffs such as g.drawLine() etc. inside class MyCanvas.java

public class MyCanvas extends JComponent{ 
   public void paint(Graphics g){...}
}

And my Main.java class is

class Main{
 public static void main(String[] args){
   JFrame window = new JFrame();

   window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   window.setBounds(30, 30, 1000, 350);
   window.getContentPane().setLayout(new FlowLayout());

   MyCanvas mc = new MyCanvas();
   JScrollPane jsp = new JScrollPane(mc);
   jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

   window.getContentPane().add(jsp);
   window.getContentPane().setBackground(Color.WHITE);
   window.setVisible(true);
 }
}

However, JFrame is only showing white plain background, It isn't showing any Graphics stuff from paint(Graphics g).

Note that, If I remove JScrollPane from above Main.java, then it shows everything perfectly.

class Main{
 public static void main(String[] args){
   JFrame window = new JFrame();

   window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   window.setBounds(30, 30, 1000, 350);

   window.getContentPane().add(new MyCanvas());
   window.getContentPane().setBackground(Color.WHITE);
   window.setVisible(true);
 }
}

Where my logic is going wrong? Is there any problem while adding JScrollPane ? Please help. Thanks.

Upvotes: 0

Views: 72

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

class MyCanvas extends JComponent{ 
   public void paint(Graphics g){...}
}

Should be:

class MyCanvas extends JComponent{ 
   @Override
   public void paintComponent(Graphics g){...}
}

By using paintComponent we respect the painting chain. Also be sure to add super.paintComponent(g); as the first statement in the overridden method, to assure that the BG color and borders etc. are painted.

Upvotes: 2

Related Questions