Reputation: 585
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
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