I have a class that draw some very simple graphics like lines, circles and rectangles. The lines are dynamically expandable and sometimes when they expand beyond the resolution, it is impossible to see without a scroll bar. Therefore, I've added JScrollPane to my JFrame but unfortunately, the scroll bar is not scrollable despite calling the Layout Manager already.
Here's what I have: - A class that draws components (lines, rectangles, circles) - A class that sets up the JFrame/JScrollPane
Here's an excerpt code of my GUI class:
JFrame frame = new JFrame("GUIFrame");
frame.setLayout(new BorderLayout()); // Layout already set
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawComponent comp = new DrawComponent(); // Reference to class that draw components
JScrollPane sp = new JScrollPane(comp, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
sp.setPreferredSize(new Dimension(1000, 1000));
frame.add(sp, BorderLayout.CENTER);
frame.setSize(500,500);
frame.setVisible(true);
With the code above, I've got Java to show me a JFrame with scrollpane containing my jcomponents. I have set the scrollbars to always appear as shown above but they are not scrollable, gray-ed out.
As suggested by Andrew, I took sometime to create a SSCCE to reflect what I'm trying to do:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class DrawTest {
public static void main(String[] args){
JFrame frame = new JFrame("SSCCE");
frame.setLayout(new BorderLayout());
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawComp d = new DrawComp();
JScrollPane sp = new JScrollPane(d, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(sp);
frame.setVisible(true);
}
}
class DrawComp extends JComponent {
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
Random ran = new Random();
int ranNum = ran.nextInt(10);
System.out.println(ranNum);
double length = 100 * ranNum;
g2.draw(new Line2D.Double(10, 10, length, length));
}
}
The code above draws a diagonal line based on a random input. What I intend to do is that when the line gets so long that it goes out of the frame size, I hope that I'll be able to scroll and have a view of the full line. Again I have added the line component to JScrollPane but it's not scroll-able.