Setting JScrollPane position

I have a JScrollPane which has a JList (of sorted strings) as its view. When the list has the focus and the user presses a key, the first item that starts with the pressed key is selected. But the the JScrollPane does not scroll to this position and I'd like to add this feature.
What I have tried is (in valueChanged())
scrollPane.getVerticalScrollBar().setValue(list.getSelectedIndex());but this does not work. How can I set the scroll position to a certain value?

What I have tried is (in valueChanged())Show the sample program you used to test your code. It works fine for me:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class ListScrollToSelected extends JFrame implements ListSelectionListener
    public ListScrollToSelected()
        String[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
        JList list = new JList( data )
            public int getNextMatch(String prefix, int startIndex, Position.Bias bias)
                int row = super.getNextMatch(prefix, startIndex, bias);
//                ensureIndexIsVisible( row );
                return row;
        list.setVisibleRowCount(5);
        list.setSelectedIndex(0);
        list.addListSelectionListener( this );
        JScrollPane scrollPane = new JScrollPane( list );
        getContentPane().add( scrollPane );
    public void valueChanged(ListSelectionEvent e)
        if (e.getValueIsAdjusting()) return;
        JList list = (JList)e.getSource();
        list.ensureIndexIsVisible( list.getSelectedIndex() );
    public static void main(String[] args)
        ListScrollToSelected frame = new ListScrollToSelected();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
}I also included a second way to do this by overriding the getNextMatch(...) method.

Similar Messages

  • Problem in setting desired position for JPanel in JScrollPane!!!

    Dear Friends,
    I am having problem to set desired Scrollable(JScrollPane) JPanel position. I have a JPanel in a JFrame which is scrolable with lot of objects. It automatically displays on the top position inside JScrollPane, I want to set scroll position on the middle for the panel.
    I went through the search for the same in this forum, i found some posts related to this but they are linked with JTextArea(setCaretPosition). With JPanel i can't set caret position.
    Could anyone guide me how to set the scroll position on middle.
    Regards..
    Jayshree

    Replace:
    if(view.getValueAt(row,column) instanceof ImageIcon){
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
          }with:
    if(view.getValueAt(row,column) instanceof ImageIcon)
            view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
           view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

  • How do you set the position of JScrollBars?

    Can anyone tell me how to set the positions of the JScrollBars in a JScrollPane so that it will show the area I want?
    please,
    Tommy

    Sorry i should of add the area I am talking about is a JPanel.

  • How to set the position in SAP Script

    Hi Professionals,
    Can anyone tell me that How can I set the position of an bitmap Image (after inserting) in SAP Script ?
    by default position is in Left, I need to align it in center or somewhere else.
    Anybody knows, kindly reply!
    Thanks
    Devinder

    Hi,
    But Can we assign a window under another window. Because I want to insert a bmp picture on particular position.
    example:- there is a digital signature and wanted to insert upon a name.
    So, there is a text (which is customer name) and digital signature (in bmp picture format) upon it.
    Thanks
    Devinder

  • I need to set the position of components on a page that contains a MenuBar,

    I need to set the position of components on a page that contains a MenuBar, but MenuBar does not provide a getPreferred size method.
    How can I get the MenuBar's size in AWT?
    Thanks.

    A menubar is not a general component that is added to a frame like any another. It is the specific responsibility of the setMenuBar/setJMenuBar methods to deal with this.

  • Set file position within a for loop, error 1

    Hi, I'm reading from a .sxm file consisting of a large chunk of text followed by binary data for 512x512 images with 4 bytes per pixel
    I’ve managed to successfully identify the start of the binary and read the first image from the file and view it using  "flatten pixmap.vi", so I’m doing something right, however when i try to read the next chunk of image data in the .sxm file using a for loop, set file position keeps churning out ERR (1).
    im at a loss as to whats causing this
    Solved!
    Go to Solution.
    Attachments:
    binaryread3d trouble.vi ‏22 KB
    back panel screenshot.png ‏27 KB

     I closed the file in the loop, doh! ... another morning well spent

  • Set audio position microseconds/Player

    Hay,
    I've made this nifty little class for playing audio:
    import java.io.*;
    import javax.sound.sampled.*;
    public class Player implements LineListener
         // Consts
         public static final float maxVol = 6.0206f;
         public static final float minVol = -80.0f;
         // Vars
         // The AudioInputStream to play
         private AudioInputStream toPlay = null;
         // If the playthread should pause
         private volatile boolean paused = false;
         // If the thingy is playing
         private volatile boolean playing = false;
         // The line
         private volatile SourceDataLine line = null;
         // The thread that will play the sound
         private Thread playThread = null;
         // Construtor
         // Body
         public void play(String toPlay)
              try {
                   // If playing
                   if (playing && paused && (!line.isRunning())) {
                        setPaused(false);
                        // The return so don't play again
                        return;
                   play(new FileInputStream(toPlay));
              } catch (Exception ex) {ex.printStackTrace();}
         public void play(File toPlay) {
              try {
                   // If playing
                   if (playing && paused && (!line.isRunning())) {
                        setPaused(false);
                        // The return so don't play again
                        return;
                   play(new FileInputStream(toPlay));
              } catch (Exception ex) {ex.printStackTrace();}
         public void play(InputStream toPlay) {
              try {
                   // If playing
                   if (playing && paused && (!line.isRunning())) {
                        setPaused(false);
                        // The return so don't play again
                        return;
                   // Get AudioInputStream from given file.
                   this.toPlay = AudioSystem.getAudioInputStream(toPlay);
              } catch (Exception ex) {ex.printStackTrace();}
              // Make the play thread
              playThread = new Thread(new PlayThread());
              // Start it
              playThread.start();
         public void stop()
              // Not playing
              playing = false;
              // If there is a line
              if (line != null)
                   // Close the line
                   line.close();
                   line = null;
              // Distroy the play thread
              playThread = null;
         public void update(LineEvent e)
              // Stop
              if (e.getType()==LineEvent.Type.STOP)
                   stop();
         // Getters
         public SourceDataLine getLine()
              if (line != null)
                   return line;
              return null;
         public float getVolume()
              FloatControl con = (FloatControl) line
                        .getControl(FloatControl.Type.MASTER_GAIN);
              // Get value
              return con.getValue();
         public boolean getMute()
              BooleanControl con = (BooleanControl) line
                        .getControl(BooleanControl.Type.MUTE);
              // Get
              return con.getValue();
         // Setters
         public void setPaused(boolean inPaused)
              paused = inPaused;
              // If not null
              if (line != null)
                   // If paused
                   if (paused)
                        // Stop the line
                        line.stop();
                   } // Resume
                   else
                        // Start
                        line.start();
         // Setters
         public void setVolume(float vol)
              // TODO: Maybe test to see if within min an max
              FloatControl con = (FloatControl) line
                        .getControl(FloatControl.Type.MASTER_GAIN);
              // Set value
              con.setValue(vol);
         public void setMute(boolean mute)
              BooleanControl con = (BooleanControl) line
                        .getControl(BooleanControl.Type.MUTE);
              // Set
              con.setValue(mute);
         private class PlayThread implements Runnable
              public void run()
                   try {
                        System.out.println("toPlay is null " + (toPlay == null));
                        // If not playing
                        if (!playing)
                             // Now playing
                             playing = true;
                             play();
                        System.out.println("Finished");
                   } catch (Exception ex) {ex.printStackTrace();}
              private void play()
                   try {
                        AudioInputStream din = null;
                        if (toPlay != null)
                             AudioFormat baseFormat = toPlay.getFormat();
                             AudioFormat decodedFormat = new AudioFormat(
                                       AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                                 .getSampleRate(), 16, baseFormat
                                                 .getChannels(),
                                       baseFormat.getChannels() * 2, baseFormat
                                                 .getSampleRate(), false);
                             // Get AudioInputStream that will be decoded by underlying
                             // VorbisSPI
                             din = AudioSystem
                                       .getAudioInputStream(decodedFormat, toPlay);
                             // Play now !
                             rawplay(decodedFormat, din);
                             toPlay.close();
                   } catch (Exception e) {e.printStackTrace();}
              private void rawplay(AudioFormat targetFormat, AudioInputStream din)
                        throws IOException, LineUnavailableException
                   byte[] data = new byte[4096];
                   line = getLine(targetFormat);
                   if (line != null)
                        // Start
                        line.start();
                        int nBytesRead = 0, nBytesWritten = 0;
                        while (nBytesRead != -1)
                             // While still paused
                             while (paused) {}
                             nBytesRead = din.read(data, 0, data.length);
                             if (nBytesRead != -1)
                                  nBytesWritten = line.write(data, 0, nBytesRead);
                        // Stop
                        line.drain();
                        line.stop();
                        line.close();
                        din.close();
              private SourceDataLine getLine(AudioFormat audioFormat)
                        throws LineUnavailableException
                   SourceDataLine res = null;
                   DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                             audioFormat);
                   res = (SourceDataLine) AudioSystem.getLine(info);
                   res.open(audioFormat);
                   return res;
    }I've got an app that uses JMF to play MP3's, but using JMF just to play MP3's is overkill, but I've found a SPI from javaZoom now, so that's okay.
    Anyway, I want to set the position of the line in microseconds now, as well as get the duration.
    Can anyone help with this?
    By the way, if anyone can open .rar files (lots of complainants about that) then the, in much need of an update, app is here: http://acquiesce.awardspace.co.uk/Projects/Download/Music_Exploder.rar
    I you do want to try it, you do need the JMF.
    Why not pop into the forum as well:
    http://acquiesce.informe.com/mucic-exploder-dc4.html
    You know I need the comments.
    Luke :D

    okay, so u can do this in the Clip interface, but the Clip takes ages to open, at lest for mp3's.
    I need it to open it right away
    I understand a bit more now, the SourceDataLine plays each byte as it is writen which is why it plays it straight away, but the Clip loads it into memory, so therefore it knows how long, how many frames etc about the audio, but it means that it's not as fast as streaming.
    I need the best of both worlds really, I've tried opening a Clip on another Thread as well as playing from a SourceDataLine, the idea was to have the Clip take over the playing once it has loaded, but the line doesn't play or read/write.
    Is there someway to take advantage of both streaming an non-streaming in this way?
    Or simply make the Clip.open_AudioImputStream) faster?
    Thanks
    Luke

  • Setting Cursor position

    Pls help me for the following query:
    how to set cursor position at the beginning of text field(JTextField) after setting text inside it.

    RTFM
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition(int)

  • Set file position error

    Hi,
    I am using LabVIEW 2009 SP1 on Win XP OS system. I am reading and writing data to a text file whose size does not exceed 50 MB. whenever i try to set file position to a value of say 128 bytes from the start of file, the function does not show an error. But when i try to read back the file position using get file position function, the value shows a very high number. I am not able to do a random access read of the file data. Please help.
    Regards,
    Yashasvi

    Hi Yashasvi,
    can you post the vi (or vi section) causing the problem?
    Thanks,
    Marco

  • Setting tab position and alignment in one shot

    Is there anyway to add a tab and set the position and alignment at once?
    myParagraph.tabStops.add().position = myTabPosition;
    The problem I am having is I don't know how to reference the tab to set
    its alignment.

    Hi Fred,
    It'll work on most add() operations--it's our attempt at adding the AppleScript "with properties" statement to JavaScript.:-)
    Thanks,
    Ole

  • Custom Script - set object position

    Hello,
    I want to build a trasformation that set a position of an'object (entity, table, ..) in diagram. Any idea?
    Thank you.
    (sorry for my english)
    Davide

    It sounds like you want to use a default or derived attribute value.
    You set these in rules, which are applied via profiles.
    http://docs.oracle.com/cd/E23943_01/doc.1111/e10978/c04_metadata.htm#DAFIIEEI
    let me know if this helps!
    -ryan

  • Set cursor position in console

    Hello,
    I would like to set the position of the cursor in the console (command prompt).
    Is ther a way to do this ?
    public void printChar(int x, int y, char ch) {
         <set cursor position>(x,y);
             System.out.println(ch);
        }Thanks

    Ymas wrote:
    Do i have to add something like import java.???
    No, nothing starting with "java.*" will help you. There is no way you can do that using only what Java provides itself, you will need to use external libraries.
    Chances are, you don't want to do this right now and forget about it, just write one line after another.
    If it s not too long could you write me the code for <*set cursor position*>(x,y);Find, download, learn to use JCurses or a similar library and write it. If that sounds like a lot of work for such a "simple" functionality then yes: that is a lot of work for such a little thing.
    It's generally not worth doing.

  • Applescript bug in setting button positions in iDVD6

    I took the liberty of downloading the project files for Apple's iDVD Companion (http://www.apple.com/applescript/idvd/companion.html) to remove the annoying limitations on setting button positions (the original app would allow a maximum horizontal offset of 512 and vertical offset of 384, which is too constraining in widescreen projects)
    After updating the project in Xcode and fixing some Applescript bugs, I modified the code to allow button positions up to (936, 484) which is the lower right corner in a widescreen project.
    But it turns out Apple hasn't modified iDVD's scripting to allow button positions in excess of (620, 480). No doubt this was set when iDVD was first made scriptable - BEFORE the advent of widescreen projects!
    So in iDVD Companion now, if I set a button position to be (936, 484), the button only moves to (620, 480) and stops. No errors are generated.
    The other curiosity is that in a widescreen project the left hand edge of the screen is not offset 0 but an offset of 80. Explain that!
    I'll report this to Apple.

    Yes, you are right!
    If you write an Applescript to directly address iDVD6 using its Dictionary commands, you can indeed read button positions greater than (620, 480) (eg, if you manually drag a button to the extreme right hand side of a widescreen project) but you can't write button positions greater than (620, 480) - anything over that is truncated.
    Well spotted... definitely a bug.

  • Set Labels Position

    Hi all,
    Is there no way I can set the position of the labels on my form.
    Thanks
    Jideofor

    Ah... but your forgetting about the Law of Diminishing Return. The larger the cup, the larger the vehicle needed for transporting it. Once the cup reaches the size of a 18-wheel semi tractor trailor you may wish you had gotten a smaller cup.... not to mention the affects of drinking all that coffee!
    ;)

  • JScrollPane - can you set scroll position?

    I have a JList loaded into a JScrollPane, and I call a method that highlights a row of the JList, but I can't figure out how to get the JScrollPane to scroll down.
    Is there a method where I can manually set the scroll position? I looked at the documentation online and didn't see anything like that.
    Thanks.
    -Mark

    You need to get a reference to the JScrollPane's JViewport
    myPane.getViewport();
    Then on the viewport you can call one of these.
    scrollRectToVisible(Rectangle contentRect)
    setViewPosition(Point p)
    Cheers,
    Rachel

Maybe you are looking for

  • Running Itunes library on a new computer off of an external hard drive

    Hello, I've recently purchased a Macbook and an external hard drive. I transferred all my files from my old Mac onto my external and would like to try to run my itunes library from there through my new laptop as opposed to putting all the files onto

  • PayloadZipBean in SFTP sender adapter

    The senario is : the sender channel uses the ZIP module. The sender and receiver adapters are SFTP and there is no Message mapping. The sender channel zips the text file. However the Sender cahnnel is green is Communication cannel monitoring but fail

  • Cant open Apps in iMack

    I purchased some Apps from the App store sync it to my iMack and from there to my iTouch4.They work fine in the iTouch,but should I not be able to open them in my iMack as well?

  • FF updates happen way, way too often

    Firefox 13 arrived and well, like suspected, plug-ins/add-ons are not compatible. Most important one for me is Kaspersky Anti Banner. So back to FF 12 for me. Mozilla states that companies have more then enough time to alter their software: 6 weeks.

  • Ios5 work on 3GS very slow specially use chinese word

    can i down grade ios5 to ios4 because ios5 work in 3GS very slow specially use Chinese word key pad on sms or note,some time wait until 10s will appear the word wasted my time. ios5 very slow in 3GS open app,app using.