JScrollBar method

does anyone know what JScrollBar uses to scroll a JScrollPane? I tried to make my own scroll bar but obviously used the wrong technique because Im getting a lot of weird bugs when I scroll with it that I dont get with the custom bar.

here is an example of my problem, sorry for the lengthy code but you can run it to see the problem.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Test
     public static int RIGHT = 1;
     public static int LEFT = -1;
     public static void main(String[] args)
          Test t = new Test();
          JFrame frame = new JFrame("Test");
          try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());SwingUtilities.updateComponentTreeUI(frame);}catch(InstantiationException e){}catch(ClassNotFoundException e){}catch(IllegalAccessException e){}catch(UnsupportedLookAndFeelException e){}
          frame.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});
          ContainerExplorer ce = t.new ContainerExplorer();
          JPanel p = new JPanel();
          p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
          p.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          ce.add(t.new Container(frame));
          p.add(ce);
          frame.getContentPane().add(p);
          frame.pack();
          frame.setVisible(true);
     public class Container extends JPanel
          private Image image;
          public Container(JFrame f)
               super();
               setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
               JButton b = new JButton("ty");
               add(b);
               image = makePicture("Images/Container.gif",f);
               setPreferredSize(new Dimension(image.getWidth(null),image.getHeight(null)));
               setMinimumSize(getPreferredSize());
          public void paintComponent(Graphics g)
               g.drawImage(image,0,0,null);
     public Image makePicture(String fileName,JFrame f)
          Toolkit toolkit = Toolkit.getDefaultToolkit();
          Image image = toolkit.getImage(fileName);
          MediaTracker mediaTracker = new MediaTracker(f);
          mediaTracker.addImage(image, 0);
          try
               mediaTracker.waitForID(0);
          catch (InterruptedException e){System.err.println(e);}
          return image;
     public class ContainerExplorer extends JPanel implements Runnable
          private Thread scrollThread;
          private int scroll;
          private JScrollPane scrollPane;
          private ContainerPanels containers;
          private Component selection;
          public ContainerExplorer()
               super();
               setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
               setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
               setBackground(Color.white);
               scrollThread = new Thread(this);
               scroll = 0;
               add(new ScrollPanel(LEFT));
               scrollPane = new JScrollPane(containers = new ContainerPanels());
               scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
               scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
               add(scrollPane);
               add(new ScrollPanel(RIGHT));
               scrollThread.start();
          public void add(Container c)
               JPanel p = new JPanel();
               p.setLayout(new BorderLayout());
               p.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.gray,Color.black));
               p.add(c);
               containers.add(p,BorderLayout.CENTER);
          public void run()
               int counter = 0;
               while(true)
                    if(scroll != 0)
                         scrollPane.getHorizontalScrollBar().setValue(scrollPane.getHorizontalScrollBar().getValue()+scroll);
                         if(counter > 3 && Math.abs(scroll) < 7)
                              if(scroll > 0)
                                   scroll+=1;
                              else if(scroll < 0)
                                   scroll-=1;
                              counter = 0;
                    counter++;
                    Thread.yield();
          public class ContainerPanels extends JPanel
               public ContainerPanels()
                    super();
                    setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
                    setBackground(Color.black);
               public void paintComponent(Graphics g)
          public class ScrollPanel extends JLabel implements MouseListener
               private int direction;
               public ScrollPanel(int d)
                    super();
                    direction = d;
                    if(direction == Test.RIGHT)
                         setIcon(new ImageIcon("Images/Right.gif"));
                    if(direction == Test.LEFT)
                         setIcon(new ImageIcon("Images/Left.gif"));
                    addMouseListener(this);
               public void mouseEntered(MouseEvent e)
                    scroll = direction;
               public void mouseExited(MouseEvent e)
                    scroll = 0;
               public void mouseClicked(MouseEvent e){}
               public void mousePressed(MouseEvent e){}
               public void mouseReleased(MouseEvent e){}
}

Similar Messages

  • Double Scroll Bars, Side By Side, End To End, In A JScrollPane

    I'm trying to create double scroll bars next to each other, end to end. One scroll bar is for the position in the grid, while the other, smaller scroll bar controls the zoom level. I am masquerading a JPanel as a JScrollBar. I'm adding two scroll bars to the panel, and encapsulating the panel in a subclass of JScrollBar. You might wonder why I would do that. Because JScrollPane only accepts JScrollBar classes in setHorizontalScrollBar() and setVerticalScrollBar(). I tried to override every painting method I could think of that was important, but when I test it, nothing is shown. It is completely blank. Here is the code below. I know I still have to override the general JScrollBar methods and pass them to the primary scrollbar. Does anyone have any ideas on how to do somethink like I am attempting to do?
    import java.awt.*;
    import javax.swing.*;
    import java.lang.reflect.*;
    * <p>Title: </p>
    * <p>Description: This class masquerades as a JScrollBar, but it wraps two scrollbars next to each other. The
    * main scrollbar, and the secondary scrollbar which is smaller. Any calls which treat this as a regular scrollbar
    * will return the main scrollbar's values, while the special methods can be used to return the seondary scrollbar's
    * values.
    * </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class DoubleScrollBar extends JScrollBar {
      JPanel panel = new JPanel();
      JScrollBar primary;
      JScrollBar secondary;
      public DoubleScrollBar(int orientation) {
        init(orientation);
      void init() {
        panel.setLayout(new GridBagLayout());
        if ( orientation == JScrollBar.HORIZONTAL ) {
          primary = new JScrollBar(JScrollBar.HORIZONTAL);
          secondary = new JScrollBar(JScrollBar.HORIZONTAL);
          GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.75, 0.0,
              GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
          panel.add(primary, gbc);
          gbc.gridx = 1;
          gbc.weightx = 0.25;
          gbc.anchor = GridBagConstraints.EAST;
          panel.add(secondary, gbc);
        } else if ( orientation == JScrollBar.VERTICAL ) {
          primary = new JScrollBar(JScrollBar.VERTICAL);
          secondary = new JScrollBar(JScrollBar.VERTICAL);
          GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.75,
              GridBagConstraints.NORTH, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0);
          panel.add(primary, gbc);
          gbc.gridy = 1;
          gbc.weighty = 0.25;
          gbc.anchor = GridBagConstraints.SOUTH;
          panel.add(secondary, gbc);
      public Dimension getPreferredSize() {
        return panel.getPreferredSize();
      public void setPreferredSize(Dimension d) {
        panel.setPreferredSize(d);
      public Dimension getSize() {
        return panel.getSize();
      public void paint(Graphics g) {
        panel.paint(g);
      public void paintAll(Graphics g) {
        panel.paintAll(g);
      protected void paintComponent(Graphics g) {
        try {
          Method m = panel.getClass().getMethod("paintComponent", new Class[] {Graphics.class});
          m.invoke(panel, new Object[] {g});
        catch (SecurityException ex) {
          System.out.println("SecurityException");
        catch (NoSuchMethodException ex) {
          System.out.println("NoSuchMethodException");
        catch (InvocationTargetException ex1) {
          System.out.println("InvocationTargetException");
        catch (IllegalArgumentException ex1) {
          System.out.println("IllegalArgumentException");
        catch (IllegalAccessException ex1) {
          System.out.println("IllegalAccessException");
      public void paintComponents(Graphics g) {
        panel.paintComponents(g);
      public void repaint(long tm, int x, int y, int w, int h) {
        if ( panel != null ) {
          panel.repaint(tm, x, y, w, h);
      public int getWidth() {
        return panel.getWidth();
      public int getHeight() {
        return panel.getHeight();
      public static void main(String[] args) {
        JFrame f = new JFrame();
        DoubleScrollBar dsb = new DoubleScrollBar(JScrollBar.HORIZONTAL);
        dsb.setPreferredSize(new Dimension(200, 50));
        f.getContentPane().add(dsb);
        f.pack();
        f.show();

    I know this isn't zooming, but maybe it will help.import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      MyPanel mp = new MyPanel();
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        JScrollBar jsb = new JScrollBar();
        jsb.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent ae) {
            mp.setSize(ae.getValue()*5);
        content.add(jsb, BorderLayout.EAST);
        mp.setPreferredSize(new Dimension(500,500));
        content.add(new JScrollPane(mp), BorderLayout.CENTER);
        setSize(300, 300);
      public static void main(String[] args) { new Test3().setVisible(true); }
    class MyPanel extends JPanel {
      int size;
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawRect(10,10,size,size);
      public void setSize(int size) {
        this.size=size;
        repaint();
    }

  • Scroll bar....isn't in the JScrollBar...why?

    Hey, Ive created a perfect scroll bar, in a swing app, it looks perfect...except in my JScrollBar, there are no bars....why?
    Here's my code...
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Beginning of Code~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Summary description for gui
    public class MapEditor extends JFrame
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane3;
    private JButton jButton2;
    private JButton jButton3;
    private JButton jButton6;
    private JButton jButton7;
    private JButton jButton8;
    private JButton jButton9;
    private JButton jButton10;
    private JButton jButton11;
    private JButton jButton12;
    private JPanel contentPane;
    // TODO: Add any attribute code to meet your needs here
    public MapEditor()
         super();
         initializeComponent();
         // TODO: Add any constructor code after InitializeComponent call
         this.setVisible(true);
    private void initializeComponent()
         jScrollPane1 = new JScrollPane();
         jScrollPane3 = new JScrollPane();
         jButton2 = new JButton();
         jButton3 = new JButton();
         jButton6 = new JButton();
         jButton7 = new JButton();
         jButton8 = new JButton();
         jButton9 = new JButton();
         jButton10 = new JButton();
         jButton11 = new JButton();
         jButton12 = new JButton();
         contentPane = (JPanel)this.getContentPane();
         // jScrollPane1
         // jScrollPane3
         // jButton2
         jButton2.setText("Rock");
         jButton2.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton2_actionPerformed(e);
         // jButton3
         jButton3.setText("Grass");
         jButton3.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton3_actionPerformed(e);
         // jButton6
         jButton6.setText("Grass2");
         jButton6.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton6_actionPerformed(e);
         // jButton7
         jButton7.setText("Water 1");
         jButton7.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton7_actionPerformed(e);
         // jButton8
         jButton8.setText("Path");
         jButton8.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton8_actionPerformed(e);
         // jButton9
         jButton9.setText("Water 3");
         jButton9.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton9_actionPerformed(e);
         // jButton10
         jButton10.setText("Dirt");
         jButton10.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton10_actionPerformed(e);
         // jButton11
         jButton11.setText("Snow");
         jButton11.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton11_actionPerformed(e);
         // jButton12
         jButton12.setText("Water 2");
         jButton12.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton12_actionPerformed(e);
         // contentPane
         contentPane.setLayout(null);
         addComponent(contentPane, jScrollPane1, 0,0,476,408);
         addComponent(contentPane, jScrollPane3, 476,86,248,290);
         addComponent(contentPane, jButton2, 476,1,83,28);
         addComponent(contentPane, jButton3, 559,1,83,28);
         addComponent(contentPane, jButton6, 643,1,83,28);
         addComponent(contentPane, jButton7, 476,30,83,28);
         addComponent(contentPane, jButton8, 476,58,83,28);
         addComponent(contentPane, jButton9, 643,30,83,28);
         addComponent(contentPane, jButton10, 643,58,83,28);
         addComponent(contentPane, jButton11, 559,58,83,28);
         addComponent(contentPane, jButton12, 560,30,83,28);
         // gui
         this.setTitle("gui - extends JFrame");
         this.setLocation(new Point(0, 0));
         this.setSize(new Dimension(729, 627));
    /** Add Component Without a Layout Manager (Absolute Positioning) */
    private void addComponent(Container container,Component c,int x,int y,int width,int height)
         c.setBounds(x,y,width,height);
         container.add(c);
    // TODO: Add any appropriate code in the following Event Handling Methods
    private void jButton2_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton3_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton6_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton7_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton8_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton9_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton10_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton11_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton12_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    // TODO: Add any method code to meet your needs in the following area
    public static void main(String[] args) {
              new MapEditor();
    }

    Hi,
    please use code tag when posting so much code.
    It eases a lot reading your code.
    Hey, Ive created a perfect scroll bar, in a swing app,
    it looks perfect...except in my JScrollBar, there are
    no bars....why?basically because there is nothing to scroll and even to view !!
    nowhere in your code appears a call to :
    jScrollPane1.setViewportView(Component view);
    Moreover the scroll bar appearance policy, by default is when needed.
    When needed means that if the component prefered size you wish
    to view is greater than the one of the JScrollPane, they will appear
    otherwise they won't.
    So, what would you like to see in you JScrollPane ? the buttons ?
    regards,

  • Determine preferred size to be set for the JPanel attached to JScrollBar

    Determine what preferred size to be set for the JPanel attached to JScrollBar.
    Hello all, I am having a JPanel, where new components will be added into it during run-time. When there are too many components inside the JPanel, I need to re-set the JPanel preferred size so that the JScrollBar is scrollable.
    I was wondering what is the good method to determine the preferred size of JPanel during runtime?
    Currently, I am using
    myJPanel.setPreferredSize(new Dimension(
    numberOfNewComponent * preferred width of each component,
    numberOfNewComponent * preferred height of each component
    ));Is there any better alternative?
    Thank you very much.
    yccheok

    Usually a container such as JPanel will calculate its own preferred size from its layout manager - calling setPreferredSize is often unnecessary.
    When you add a component to your JPanel its preferred size will change automatically.
    What's wrong with the behaviour when you simply add your JPanel to a JScrollPane and let it manage its own preferred size?
    Hope this helps.

  • Passing methods to methods?

    I use to program in C++ once upon a time, and one of my favorite tricks was storing procedures in pointers so I could call procedures in parent classes from a sub class.
    Parent (say a scroll bar)
    updatePosition(int)
    child (one of the buttons)
    The child could call the updatePosition() procedure because I would pass it into the child class when I made it. It allowed me to make a button that could activate anything in my code, which was useful.
    Now I'm using Java and I wanted to do something similiar. I'm trying to make a graphical scroll bar (I plan on it's dimensions to change while it's in use, so it can't be an AWT or Swing scrollbar), and I've got some buttons made. I want to do this:
    MyScrollBar {
    int position = 0;
    void updatePosition(int amount) {
    position += amount;
    MyButton upbtn = new MyButton(updatePosition);
    MyButton downbtn = new MyButton(updatePosition);
    Just assume MyButton will respond to mouse clicks (it's workings doesn't matter really). When upbtn is clicked, I want it to be able to call the method in MyScrollBar that I passed into it when it was made. Short of making a MyButton that accepts a MyScrollBar passed to it, is there a way to call the procedure in it's parent?

    I ran into a similar problem, but I used a little trick. Make another class in that same .java file that your making which holds a static variable, where your main method sets up that JScrollbar, assigns it as a variable in that class, then other parts of your code access that JScrollBar through that class.
    class MyScrollBarHolder
      public static MyScrollBar msb;
      public static void setScrollBar(MyScrollBar msbTemp)
      {msb = msbTemp;}
      public void updatePosition()
      {//your code for handling that
    }this just goes at the end of your code. Then when a button wishes to access it, you just call MyScrollBarHolder.updatePosition() or you can get the ScrollBar itself with MyScrollBarHolder.msb
    Hope this helps
    Cheers

  • JScrollBar - Issue when changing models

    Hey All-
    Well, I've come up with another interesting question which I haven't been able to resolve myself.
    Basically, I have a single view port which consists of a custom JPanel and (2) JScrollbar's. I then have multiple data and view models which are attached to each of these components. I then have a JList which has a list of all the Data/View Models. When a user selects one of the Data/View Models from the JList, that Data/View Model is attached to the JPanel and (2) JScrollbar's.
    Overall, this method seems to be working fine. When I select a new Data/View Model, the JPanel and both JScrollbar's update as expected. What happens next is unexpected though. If I then try to scroll one of the JScrollbar's, it jumps from its correct position to the last scrolled to position.
    Here is a scenario that might explain it better:
    1. Select one specific view model (which is basically a BoundedRangeModel for this scenario).
    2. Use the scrollbar and scroll to a value of 100 (keeping it simple).
    3. Select a new view model which has a value of 50 - the scrollbar now updates so instead of being located at value 100, it is now located at value 50
    4. Use the scrollbar to scroll to a new value - when clicking with the mouse on the scrollbar, the scrollbar jumps back to a value of 100 and does not move. You must click the scrollbar again to begin scrolling, yet it is only affecting the selected View/Model, and no other model.
    I have gone through all the code for the JScrollbar and its setModel() function from the Java source and there doesn't seem to be any obvious reason why this would be happening. Its almost as if the Scrollbar is somehow remembering its last scrolled to value and then jumping to this the first time you try to scroll, despite it not matching the value or extent contained within the RangeModel.
    Right now this is a minor annoyance, but I'm wondering if anyone else has experience this issue.
    Thanks!

    Well, I somehow didn't receive notice that someone had responded to this thread, so sorry for not replying back sooner.
    I did some additional digging using a simple application (which I will post below), and I have determined that this only appears to affect the Java Version 6. I have created and run the following simple test application in Netbeans using Java 6 in both Windows and Linux and have had the exhibited result above, but running Eclipse and Java 5 it appears to work fine (I use the IDE's to control which version of Java I am running).
    Here's the Code:
    package scrollbartest;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultBoundedRangeModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollBar;
    public class ScrollbarTest extends JFrame implements ActionListener {
        public JScrollBar               displayScrollBar;          
        public ScrollbarTest() {
                super();
                this.setTitle("Scrollbar Test");
                this.setLayout(new BorderLayout());
                this.setPreferredSize(new Dimension(500, 350));
                this.setSize(new Dimension(500, 350));
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                displayScrollBar = new JScrollBar();
                displayScrollBar.setOrientation(JScrollBar.HORIZONTAL);
                setModel();
                this.add(displayScrollBar, BorderLayout.NORTH);
                JButton updateButton = new JButton("Update Model");
                updateButton.addActionListener(this);
                updateButton.setVisible(true);
                this.add(updateButton, BorderLayout.SOUTH);
                this.pack();
        private void setModel() {
                DefaultBoundedRangeModel rangeModel = new DefaultBoundedRangeModel();
                rangeModel.setMinimum(0);
                rangeModel.setMaximum(100);
                rangeModel.setValue(0);
                rangeModel.setExtent(0);
                displayScrollBar.setModel(rangeModel);
        public static void main(String[] args) {
                ScrollbarTest app = new ScrollbarTest();
                app.setVisible(true);
        public void actionPerformed(ActionEvent arg0) {
                this.setModel();
    }And here's how to recreate the problem:
    1. Launch a Java application using the above as the main class.
    2. Move the scrollbar to some location other than the starting point.
    3. Click the "Update Model" button which should reset the scrollbar using a new model.
    4. Attempt to click (once) on the scrollbar position.
    At step 4, using Java 6, the scrollbar "jumps" back to the position where it was located before setting the new model. This does not appear to change the value of the new model, and it locks out any more motion of the scrollbar until you release the mouse button and press again. At this point, the scrollbar begins functioning properly, except that it is now starting at the old models value instead of the current models value (which remains 0 until you click and drag a second time).
    Using Java 5, this program works exactly as expected. My thought is that somehow the Scrollbar is keeping a reference to the old model or its values even after the model has changed for one more iteration. It seems to be the only thing that makes sense.
    In any case, any help is greatly appreciated.

  • Override scrollpane methods?

    problem: I create a time series line graph in a buffered image that has a variable width, sometimes the width is in the millions of pixels and the resulting buffered image is too large to fit into memory, even if I increase the available memory with the -Xmx1024m option. I then place the a fore mentioned buffered image into a scrollpane for viewing.
    I would like to draw only the portion of the graph that is viewable and override the scrollpane methods to redraw the image based on an x position over the total width, but I haven't found anything in the API on overriding the scrollbar or the arrow buttons. Has anyone tried this, or seen and example of how to do it?
    I am aware of products such as JFreeChart and PtolemyPlot, however I don't think either is a good fit for the project and I don't have any use for their capabilities. I am open to any other suggestions on how to accomplish this goal.
    Thanks,
    Peter

    You can try to use JScrollPane by placing a custom component extending JComponent inside the scroll pane and setting it's preferred size to the required size.
    Override paintComponent method of this component and get the view rectangle from the viewport and paint only the visible area.
    If this doesn't work you might need to use JScrollBar and write the logic yourself in this case.

  • JScrollPane method not found????

              JScrollPane scroll = new JScrollPane(someComponent);
              JScrollBar bar = scroll.getVerticleScrollBar();
              bar.setValue(bar.getMaximum());Every time the text area is appended, i want the scroller to scroll to the bottom. I have seen this solution elsewhere on the forums, but when i try to compile the program, it cannot find the method getVerticleScrollBar(), can someone please help?
    Many thanks
    Cath

    That's because that method doesn't exist. Try using getVerticalScrollBar() instead. ;)

  • JScrollBar wont scroll right

    Hi!
    I have a distributed setup where I send scrollbar positions in an application to the same application on another machine. When I try to set the scrollbars on the receiving machine it only sometimes scroll to the right position. What happens when the scrollbar is not going to the right position is that it jumps to zero (or the top if it is a vertical scrollbar). I have tried moving the scrollbar by using the method setValue on the JScrollBar class, by using the scrollbar model and by moving the viewport all with the same result.
    I am using the EventQueue(see code below) where I have a Runnable class to set the position. If I dont do this I sometimes get an ArrayIndexOutOfBounds exception proberly because I try to set the scrollbar value when another event is doing something.
    Is there any way to controll the scrollbars with out the jump to zero?
    Any other ideas how to do this?
    JScrollPane extends javax.swing.JScrollPane {
    // Some other code
    public synchronized void setState(State state) {
    if(stateHandling) {
       if(state instanceof JScrollPaneState) {
         updating = true;
         final JScrollPaneState scrollState = (JScrollPaneState)state;
         Runnable runnable = new Runnable() {
           public void run() {
           getHorizontalScrollBar().getModel().setValue( scrollState.getHorizontalValue());
           getVerticalScrollBar().getModel().setValue( scrollState.getVerticalValue()); 
           updating = false;
    EventQueue.invokeLater(runnable);
    // some other code
    } //end of class

    colLen is the number of columns in the table
    Rectangle rect = table.getCellRect(0,colLen-1,true);
    JViewport scrollView = scrollPane.getViewport();
    scrollView.setViewPosition(rect.getLocation());
    worked for me anyways :)

  • Changing Position of JScrollBar in a JScrollPane

    Hi,
    I am having a JList in a JScrollPane, and wanna to display JScrollBar on the left of JList (by default its at Right).Can I change the position of JScrollBar in a JScrollPane?
    Pl. Help
    Manoj

    Use setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
    IMHO, unless you are writing an application for Arabic/Hebrew, it's not a Good Idea (even if it's for the Lefties Guild Of America). And if it's for Arabic/Hebrew the whole display has to be swapped, and for this there is an applyComponentOrientation() method for JFrame/JDialog which acts on all components.

  • How to manage JScrollbar

    I hyave a Jtable added to a Jscrollpane. the Table is to have a very large no. (say =m) rows , but initially i get only n (n<<m) rows to populate the table. as user scroll past the n rows i will add another n rows and so on so forth till all the m rows are fetched. please help me how to set the size of tab on Jscrollbar.

    please illustrate on how to go about coding the smart
    tablemodel that will cache the data and how will the
    initial display set the tab size in the scrollbar
    according to the final limit (m)?Well, that's you job, not mine -- I have my own job ;-)
    But one can extend javax.swing.table.AbstractTableModel with a concrete
    class that uses, say an ArrayList of either ArrayLists or arrays. In your implementation
    of the TableModel method getValueAt, you would see if you've cached the data
    for that row (I'm assumg you load whole rows). If not, you would use this call as
    the trigger to load another block of data.

  • How do I change the color of a JSCrollBar

    Hi all,
    How do I change the color of a JScrollBar. I was able to change the color of the background, but not the scrollbar itself.
    Can anyone help?
    Thanks,
    R.

    Hi,
    Thanks for all your help. I actually found the sun bug report about this problem. The fix is to create a class for the JScrollBar extending JComponent and then override the setUI method.
    Here is the code for anyone who needs it:
    /* class custom JScrollBar **/
    class myScrollBar extends JScrollBar
    public myScrollBar(int orientation){
    super(orientation);
    public void setUI(BasicScrollBarUI ui) {
    super.setUI(ui);
    /* class MyUI**/
    class MyUI extends BasicScrollBarUI
    Color barColor = new Color(51,172,49);
    Color bgColor = new Color(245,245,245);
    protected JButton createDecreaseButton(int orientation) {
    return new ArrowButton(orientation);
    protected JButton createIncreaseButton(int orientation){
    return new ArrowButton(orientation);
    JButton up_button = (JButton)createIncreaseButton(SwingConstants.NORTH);
    JButton down_button = (JButton)createDecreaseButton(SwingConstants.SOUTH);
    JButton left_button = (JButton)createDecreaseButton(SwingConstants.WEST);
    JButton right_button = (JButton)createIncreaseButton(SwingConstants.EAST);
    protected void paintThumb(Graphics g,JComponent c,Rectangle thumbBounds)
    g.setColor(barColor);
    g.fill3DRect((int)thumbBounds.getX(),(int)thumbBounds.getY(),
    (int)thumbBounds.getWidth(),(int)thumbBounds.getHeight(),true);
    protected void paintTrack(Graphics g,JComponent c,Rectangle trackBounds)
    g.setColor(bgColor);
    g.fillRect((int)trackBounds.getX(),(int)trackBounds.getY(),
    (int)trackBounds.getWidth(),(int)trackBounds.getHeight());
    * ArrowButton is used for the buttons to position the
    * document up/down. It differs from BasicArrowButton in that the
    * preferred size is always a square.
    private class ArrowButton extends BasicArrowButton {
    public ArrowButton(int direction) {
    super(direction);
    public void paint(Graphics g) {
    System.out.println("i am inside the button paint");
    g.setColor(new Color(51,172,49));
    g.fill3DRect(0, 0, this.getSize().width, this.getSize().height, true);
    int w = this.getSize().width;
    int h = this.getSize().height;
    int size = Math.min((h - 4) / 3, (w - 4) / 3);
    size = Math.max(size, 2);
    g.setColor((new Color(0,0,0,0)).darker());
    paintTriangle(g,(w - size) / 2,(h - size) / 2,size+1,this.direction,true);
    public void paintTriangle(Graphics g,int x,int y,int size,int direction,boolean isEnabled){
    g.setColor((new Color(0,0,0,0)).darker());
    super.paintTriangle(g,x,y,size,direction,isEnabled);
    public Dimension getPreferredSize() {
    int size = 16;
    if (scrollbar != null) {
    switch (scrollbar.getOrientation()) {
    case JScrollBar.VERTICAL:
    size = scrollbar.getWidth();
    break;
    case JScrollBar.HORIZONTAL:
    size = scrollbar.getHeight();
    break;
    size = Math.max(size, 5);
    return new Dimension(size, size);
    in init():
    //setting the scrollbars
    MyScrollBar vertical = new MyScrollBar(JScrollBar.VERTICAL);
    MyScrollBar horizontal = new myScrollBar(JScrollBar.HORIZONTAL);
    horizontal.addAdjustmentListener(new ScrollHandler());
    vertical.addAdjustmentListener(new ScrollHandler());
    vertical.setUI(new MyUI());
    horizontal.setUI(new MyUI());
    vertical.setBorder(BorderFactory.createLineBorder(grayColor));
    horizontal.setBorder(BorderFactory.createLineBorder(grayColor));
    scrollPane.setHorizontalScrollBar(horizontal);
    scrollPane.setVerticalScrollBar(vertical);
    I hope it helps others.
    R.

  • Changing the color and size of JScrollBar

    Hi everyone,
    I have a JTextArea in a JScrollPane. I want to change the default size and color of the JScrollBar that appears. Basically, I want to customize my JScrollBar.
    Is there any method to do it or do I have to write my own JScrollPane that would show the JScrollBar I want ???
    Please , help me out.
    Many thanks in advance.
    Ramesh

    The following code shows how to change several aspects of scrollbars.
    Note the loop that prints out all the values that can be modified with simply puts to the UIDefaults table for scrollbars. The String "ScrollBars " can be changed to many other swing component names (minus the 'J') to examine their key/value pairs
    For a more complete Look and Feel reference see - http://www.spindoczine.com/sbe/files/uts2/Chapter21html/Chapter21.htmimport java.awt.*;
    import javax.swing.*;
    import java.util.Enumeration;
    import javax.swing.plaf.ColorUIResource;
    public class UISniffer extends JFrame
       UISniffer()
          setSize(400,300);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          UIDefaults uid = UIManager.getLookAndFeelDefaults();
          for (Enumeration e = uid.keys() ; e.hasMoreElements() ;)
             String s = (String)e.nextElement();
             if(s.indexOf("ScrollBar") != -1)
                System.out.println(s + ", "+ uid.get(s).toString());
          UIManager.put("ScrollBar.foreground",
                new ColorUIResource(new Color(255,0,0)));
          UIManager.put("ScrollBar.background",
                new ColorUIResource(Color.pink));
          UIManager.put("ScrollBar.thumb",
                new ColorUIResource(Color.red));
          UIManager.put("ScrollBar.thumbDarkShadow",  
                new ColorUIResource(new Color(128,0,0)));
          UIManager.put("ScrollBar.thumbShadow",  
                new ColorUIResource(new Color(190,0,0)));
          UIManager.put("ScrollBar.thumbHighlight",
                new ColorUIResource(new Color(255,128,128)));
          UIManager.put("ScrollBar.track",
                new ColorUIResource(new Color(190,0,190)));     
          UIManager.put("ScrollBar.width", new Integer(50));
          JTextArea t = new JTextArea(text);
          JScrollPane pane = new JScrollPane(t);
          //pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
          //pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          setContentPane(pane);
       public static void main(String[] args)
          new UISniffer().setVisible(true);
       String text ="  The poor King look puzzled and unhappy, and struggled with the\n"+
    "pencil for some time without saying anything; but Alice was too\n"+
    "strong for him, and at last he panted out, `My dear! I really\n"+
    "MUST get a thinner pencil.  I can\'t manage this one a bit; it\n"+
    "writes all manner of things that I don\'t intend--\'\n\n"+
    "   What manner of things?' said the Queen, looking over the book\n"+
    "(in which Alice had put `THE WHITE KNIGHT IS SLIDING DOWN THE\n"+
    "POKER.  HE BALANCES VERY BADLY')  `That's not a memorandum of\n"+
    "YOUR feelings!\n\n"+
    "   There was a book lying near Alice on the table, and while she\n"+
    "sat watching the White King (for she was still a little anxious\n"+
    "about him, and had the ink all ready to throw over him, in case\n"+
    "he fainted again), she turned over the leaves, to find some part\n"+
    "that she could read, `--for it's all in some language I don't\n"+
    "know,' she said to herself.\n\n"+
    "   It was like this.\n\n\n"+
    "                            YKCOWREBBAJ\n\n"+
    "            sevot yhtils eht dna ,gillirb sawT`\n"+
    "              ebaw eht ni elbmig dna eryg diD\n"+
    "                  ,sevogorob eht erew ysmim llA\n"+
    "                 .ebargtuo shtar emom eht dnA\n\n\n"+
    "  She puzzled over this for some time, but at last a bright\n"+
    "thought struck her. `Why, it's a Looking-glass book, of course!\n"+
    "And if I hold it up to a glass, the words will all go the right\n"+
    "way again.'\n\n"+
    "  This was the poem that Alice read.\n\n\n"+
    "                           JABBERWOCKY\n\n"+
    "            'Twas brillig, and the slithy toves\n"+
    "              Did gyre and gimble in the wabe;\n"+
    "            All mimsy were the borogoves,\n"+
    "              And the mome raths outgrabe.\n\n"+
    "            `Beware the Jabberwock, my son!\n"+
    "              The jaws that bite, the claws that catch!\n"+
    "            Beware the Jubjub bird, and shun\n"+
    "              The frumious Bandersnatch!'\n\n"+
    "            He took his vorpal sword in hand:\n"+
    "              Long time the manxome foe he sought--\n"+
    "            So rested he by the Tumtum tree,\n"+
    "              And stood awhile in thought.\n\n"+
    "            And as in uffish thought he stood,\n"+
    "              The Jabberwock, with eyes of flame,\n"+
    "            Came whiffling through the tulgey wood,\n"+
    "              And burbled as it came!\n\n"+
    "            One, two!  One, two!  And through and through\n"+
    "              The vorpal blade went snicker-snack!\n"+
    "            He left it dead, and with its head\n"+
    "              He went galumphing back.\n\n"+
    "            `And has thou slain the Jabberwock?\n"+
    "              Come to my arms, my beamish boy!\n"+
    "            O frabjous day!  Callooh!  Callay!'\n"+
    "              He chortled in his joy.\n\n"+
    "            \'Twas brillig, and the slithy toves\n"+
    "              Did gyre and gimble in the wabe;\n"+
    "            All mimsy were the borogoves,\n"+
    "              And the mome raths outgrabe.\n\n\n"+
    "  `It seems very pretty,\' she said when she had finished it, `but\n"+
    "it\'s RATHER hard to understand!\'  (You see she didn't like to\n"+
    "confess, ever to herself, that she couldn\'t make it out at all.)\n"+
    "`Somehow it seems to fill my head with ideas--only I don\'t\n"+
    "exactly know what they are!  However, SOMEBODY killed SOMETHING:\n"+
    "that\'s clear, at any rate--\'";
    }

  • Adding buttons to JScrollBar

    Hi,
    I'm trying to add a couple of JButtons to the top of the JScrollBar, on top of the incrButton. I think I have to extend BasicScrollBarUI but I've tried different methods and I can't seem to get it to work. Anyone out there done something similar?
    Thanks

    Hi, Obtained to decide the Problem? If yes, it could pass me as conseguio to decide?
    e-mail: [email protected]

  • Make a JScrollBar only update its JScrollPane when the user releases it?

    Hi
    I have a JTable inside a JScrollpane. The JTable gets its data from my TableModel using the getValueAt method in the normal way. It is almost working fine. The one thing left to improve is that I don�t want the JTable to keep trying to get its data while the scrollbar is still being dragged. This is primarily because the latency in fetching the data makes the UI unresponsive - the table model does not keep all rows in memory at one time, but keeps a page of data in memory.
    So, just to clarify, I want the behaviour to be that when the user is still adjusting the value of the scroll bar, the thumb position of the scroll bar moves, but the rows displayed in the JTable do not update. When the user releases the scrollbar, the rows should then update.
    I have almost acheived this by having a second, independent scroll bar on the frame, and an adjustment listener listening for events, like this
    public void adjustmentValueChanged(AdjustmentEvent e){
    if (e.getSource() == scrManual){
    if (!scrManual.getValueIsAdjusting()){
      JScrollBar scrTable = scrPaneResults.getVerticalScrollBar();
    int iManValue = scrManual.getValue();
    int iManMax = scrManual.getMaximum();
    float fManWhere = (float)iManValue / (float)iManMax;
    int iTblMax = scrTable.getMaximum();
    int iTblNewValue = (int)(iTblMax * fManWhere);
      scrTable.setValue(iTblNewValue);
    else
    throw new IllegalArgumentException("I don't know how to handle the adjustment event for " + e.getSource());
    }This is actually working fine, except that I don't want there to be two scrollbars - one in the scroll pane and one extra one. But when I try to make the scrollpane's scrollbar invisible, it remains visible.
    Can anyone tell me either
    (a) how to just have a normal JScrollPane scrollbar, but have it only update its viewport when the value is no longer adjusting (ie scrollbar has been released)
    (b) how to make the JScrollPane's scrollbar still effective, but invisible.
    (c) if the JScrollPane has a no scrollbars policy, how to instead in the code I posted above, set the ScrollPane's position directly.
    Whichever is easiest.
    Thanks for your help
    Mark

    Oh how embarassing! I already asked this question before, and answered it myself! Sorry - I think I am losing the plot
    I�ve hacked it. Turns out that the jScrollPane has a getXXXScrollBar method, which even when you�ve hidden the scrollbars, still works. You just use another scroll bar, register a listener for the mouse released event, and update the jScrollPane�s scroll bar to match the value.

Maybe you are looking for

  • Suddenly, no "minimize" (yellow) button...

    I've restarted, reset and explored other Safari abnormalities. I'm stumped. My Tiger partition is giving me fits and I thought I was a smart user. The button to "minimize" has gone "clear" (maybe a diagnostic tool?) and other strange behavior (crashe

  • Sales order help needed

    Hi, I have a requirement, where client is creating a custom sales order form and my task is to write a package to book, delete and change sales order when the user presses button in the front end. The custom form calls my package when book order is p

  • Why can I not sign into the iCloud Control Panel on my Windows 8 PC?

    I am trying to sign into the iCloud Control Panel and keep getting a server error message?

  • Dual 1.8 G5 Wont boot, fans running high

    So last night i deleted a folder which was full of documents (school docs, nothing important). I then went to empty the trash and the little emptying the trash progress box popped up but nothing was happening. I was then unable to cancel the trash em

  • Problem displaying PDF with Jasper Reports

    I have the following code that loads a report and displays it in PDF format: if(jasperReport==null) {      logger.debug("Loading...");      InputStream inStream = null;      try {           inStream = getServletContext().getResourceAsStream("/WEB-INF