0

I am trying to create a program that computes for the Round Robin algorithm. The logic works fine. My problem is with the overriden JPanel that I use to draw the timeline. The timeline goes on and on without definite line length. I want to add the overriden panel to a scroll pane so it can be scrollable.

SampleGPane.class

import java.awt.*;
import javax.swing.*;

public class
SampleGPane 
{

    /* Timeline elements */
    Container timelineContainer;
    JFrame timelineFrame = new JFrame ();
    JPanel pnlDraw = new JPanel ();
    JScrollPane timelineScroll;

    public void 
    launchFrame () 
    {
        GPanel gpane = new GPanel ();
        timelineContainer = timelineFrame.getContentPane ();
        timelineScroll = new JScrollPane (gpane);
        timelineContainer.add (timelineScroll);

        timelineFrame.setSize (500, 250);
        timelineFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        timelineFrame.setVisible (true);
    }

    private class 
    GPanel extends JPanel 
    {
        @Override
        public void 
        paintComponent (Graphics g) 
        {
            super.paintComponent (g);
            int runningLineX = 0;
            int runningLineY = 0;

            // g.drawLine (50, 50, orderCount * 5, 50);

            runningLineX += 50;
            runningLineY += 50;

            for (int count = 0; count < 35; count++) {
                g.drawString ("J" + (count + 1), runningLineX + 50, 25);
                runningLineX += 50;
                // runningLineY += 50;
                g.drawLine (runningLineX, runningLineY, runningLineX + 50, runningLineY);
            }
        }
    }

}

SampleGPane.class is called by SampleLaunch.class

public class
SampleLaunch 
{
    public static void main (String args[]) {
        SampleGPane sgp = new SampleGPane ();
        sgp.launchFrame ();
    }
}

The problem is, the JScrollPane won't work. It doesn't seem to detect the line. How do I fix this?

Community
  • 1
  • 1
Bryan James
  • 65
  • 1
  • 11

1 Answers1

4

You need to override the getPreferredSize() method of your custom panel to return a reasonable size.

The scrollbars will only appear when the preferred size of the component added to the viewport of the scroll pane is greater than the size of the scroll pane.

The timeline goes on and on without definite line length.

The line length will need to match your painting code. So you need parameters to control what to paint. These parameters will also be used in the calculation of the size of the component. In your example you iterate 35 times and increment the x by 50 so the width would be 1750 plus the starting x offset.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks! This helps me fix my problem. So the key to this is to count the time spent, pass it in a constructor, the constructor will set a variable for overriding the `getPreferredSize()` method, then launch the frame. – Bryan James Feb 25 '16 at 04:23