I have a java class that extends from JPanel. The basic purpose of extending this class from JPanel is that i want to draw some graphical figures inside this JPanel. The code of this class is as follow:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class ObjectViewer extends JPanel {
public void paintComponent(Graphics g) {
//just for testing
g.drawRect(0, 0, 100, 10);
g.drawLine(150, 150, 250, 150);
}
}
Now i am loading this JPanel in JScrollPane, by using the following code.
JPanel jpnl = new ObjectViewer();
jScrollPane2.add(jpnl);//Note: I drag and drop this JScrollPanel at desired location from NetBeans gui.
But i am unable to see any graphics (Rect and Line) in that JScrollPane, any suggestions for what i am doing wrong?
You never add your JPanel directly to a JScrollPane but rather to its viewport. So for instance, not
but rather something like:
or
alternatively, you could add the JPanel as a parameter in the scrollpane’s constructor.