Reputation: 455
As the title suggests I am trying to draw on a JPanel
inside a JScrollPane
(as the panel will almost always overflow the screen so I need to be able to scroll). I'm having a weird issue in that the PaintComponent
method is not drawing as I would expect. I am currently just attempting to fill the JPanel
with a solid colour however instead of filling the JPanel
it is actually only drawing an unfilled box, as in, it is partially filled but not completely.
The code for my JPanel
(PLEASE NOTE simPanel IS THE JSCROLLPANE
):
private class myPanel extends JPanel {
@Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(0, 0, simPanel.getWidth(), simPanel.getHeight());
}
}
My WindowResizeListener
is attached to the JScrollPane
itself and runs the following method, so far it seems to be resizing correctly as I have been using print statements to get the size of the scrollpane and it is getting larger /smaller as I resize the application.
public void componentResized(ComponentEvent ce) {
myJPanel.setSize(simPanel.getSize());
}
This works as intended if the JPane
l is not added to a JScrollPane
(i.e. it is added to another JPanel
or similar) but the JScrollPane
itself does not seem to want to paint correctly. I am wondering if there is something I am missing. It looks like my JPanel
is the right size as the box is the correct size within the Scroll Pane itself I just can't fill it even though I am calling fillRect
.
EDIT: I think it might have something to do with the ScrollPane's size. I am messing around with different Layout Managers at the moment and noticing that the scroll pane is very temperamental with its size and keeps moving back to a fixed size for some reason......
Upvotes: 0
Views: 369
Reputation: 324088
The code for my JPanel (PLEASE NOTE simPanel IS THE JSCROLLPANE):
The painting code of your JPanel should NOT reference the size of the scroll pane. In any case you just use the setBackground(...)
method of the panel to set its background color.
JScrollPane (as the panel will almost always overflow the screen so I need to be able to scroll)
The scrollbars will appear automatically when the preferredSize of the panel is greater than the size of the scrollpane. The layout manager of your panel is responsible for determining the panels preferred size, so you don't need any custom code.
Upvotes: 1