Scroll 2 JScrollPanes together?

Quick question. (I hope it's quick anyway.)
I have 2 JTextAreas side by side added to JScrollPanes.
I past a list in the one on the left, click a button to do something with that list and it writes to the JTextArea on the right like a log file.
If the list is longer than the JTextArea is tall, It puts a scroll bar on the right. And when the log pane gets too long, I keep the scrollbar on it at the bottom with this line of code:
somelog.setCaretPosition(somelog.getText().length());My question is...Can I make the scrollbars of both syncronized? Because right now, only the one on the right keeps up with the bottom of it's text. I would like them both to scroll at the same time. Because there is one line of log output for each item in the list. I would like for when the log starts scrolling, the list scrolls with it so the items remain lined up.
Thanks!
Tim

Try sharing the scrollpanes' scrollbars' model
scrollList.getVerticalScrollBar().setModel(scrollLog.getVerticalScrollBar().getModel());db

Similar Messages

  • Scrolling a JScrollPane in code

    hello
    java.awt.ScrollPane has a way to send the scrollpane to a certain point in code, however, it seems to be lacking in JScrollPane. how do you scroll in JScrollPane to a certain point?
    i tried having the item ask for focus, but that didnt work.
    any ideas?

    another complication: the panel is being resized as well. while its large, the user clicks on it and i want to have it shrink down to only the selected item. so i shrink it to 37 high and scroll down as previously mentioned. however, if the selection is in the last few, its still stuck on the same extent as before (i think). so it goes down as far as it could while it was large, and no more. so i can never get to those that are only visible while large.
    thinking its the extent and/or the visible area, i changed those values and it still doesnt work.
    i know its adjustable, because, once its small, the next time i make a selection (selected while small) it scrolls and shrinks (already shrunk) to the selected item. of course, this is easy becasue it must be visible to be selected and as i said, its already shrunk.
    the problem is the first time, while its large and the selection shrinks it.
    -j

  • Implementing a graph scrolling using JScrollPane component

    I would like to ask a question apropos using of JScrollPane component. A part of the default behaviour of this component is adjusting the component's state when the size of the client changes. But, I need to achieve an opposite effect - I need to adjust a size of my client when the size of JScrollPane (and its viewport) changes (for instance, when the user resizes the frame).
    I implement a graph component which will show the graph of a time function. This component should always show nnn seconds without connection to the size of the scroll pane's viewport. So, if the the scroll pane component is resized I need to adjust the size of my client in order to keep the displayed time period unchanged.
    Now the question: how may I check the size of the viewport when the size of the JScrollPane changes? And whether I can do it even if the JScrollPane component has no client?
    If you know any other method of achieving the same effect, plese let me know.
    Thanks.

    I still find getExten\tSize (and getViewRect) work for me. Here's another demo.
    In my component, there's a big oval thats bounded by my component and a smaller
    oval that should track with the viewport's bounds.
    import java.awt.*;
    import javax.swing.*;
    public class ViewportLemonJuice extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawOval(0, 0, getWidth(), getHeight());
            Container parent = (Container) getParent();
            if (parent instanceof JViewport) {
                Rectangle rect = ((JViewport) parent).getViewRect();
                g.drawOval(rect.x, rect.y, rect.width, rect.height);
        public static void main(String[] args) {
            JComponent comp = new ViewportLemonJuice();
            comp.setPreferredSize(new Dimension(800,800));
            JScrollPane sp = new JScrollPane(comp);
            sp.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            JFrame f = new JFrame("ViewportLemonJuice");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(sp);
            f.setSize(500,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • JEditorPane not scrolling in JScrollPane no matter what

    Hello,
    I thoroughly researched this problem and I tried all suggestions, but nothing seems to work. I have a JEditorPane inside the JScrollPane, but JEditorPane does not scroll horizontally no matter what. It simply cuts off the text to the right.
    Here is my code:
    reportArea = new JEditorPane() {
    public boolean getScrollableTracksViewportWidth() {                   
    if (getSize().width < getParent().getSize().width)
         return true;
    else
         return false;
    public void setSize(Dimension d) {                   
    if (d.width < getParent().getSize().width)
         d.width = getParent().getSize().width;
    super.setSize(d);
    reportArea.setEditorKit(new HTMLEditorKit());
    reportArea.setEditable(false);
    JScrollPane reportJ = new JScrollPane(reportArea);
    reportJ.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    reportJ.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    Any suggestions will be greatly and truly appreciated!
    Elana

    I need to display HTML page, that's why I need JEditorPane. Also, In the html table that I'm displaying I have the nowrap attribute, so nothing gets wrapped at all. It's just being cut off...
    ;-(

  • Programatic scrolling in JScrollPane

    Hi all,
    I have a JPanel with a GridLayout that contains a series of other JPanels, the whole stuff looks like a list.
    JPanel masterPanel = new JPanel( new GridLayout( .. ) );
    masterPanel.add( new JPanel( .. ) );
    masterPanel.add( new JPanel( .. ) );
    masterPanel.add( new JPanel( .. ) );
    The GridLayout defines one single column, so that all the JPanels look like arranged in a list.
    The masterPanel is then embedded into a JScrollPane using
    setViewPortView( masterPanel );
    now:
    when the JFrame that contains all this is shown the first time I want the JScrollPane to be scrolled to the top.
    I tried to directly manipulate the JScrollBars (setValue( 0 ),
    I used ViewPort.setViewPosition( new Point ( 0, 0 ) ),
    I used scrollPane.scrollRectToVisible( new Rectangle( 0, 0, 20, 20 ) )
    but nothing worked so far, the scroll pane is always scrolled to the bottom ....
    I also browsed the forum but did not find anything that worked.
    Anybody any idea ?
    Andy

    I used scrollPane.scrollRectToVisible( new Rectangle(
    0, 0, 20, 20 ) )don't use the scrollPane but your masterPanel.scrollRectToVisible(...)!
    thomas

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Programmatically Scroll JScrollPane - Best Practice

    Having a bit of trouble finding the best (most foolproof/efficient/correct) way of programmatically scrolling a JScrollPane to make sure a component is visible. I've written a little demo for the solution I have at the moment and was wondering if it can be improved upon.
    The demo creates 100 clickable JLabels in the right section of the JSplitPane and 100 JLabels with the corresponding integer value in the left section. When the user clicks on a JLabel in the right section the JLabel with the corresponding value in the left section is highlighted red in foreground colour and if the label isn't currently visible the scroll pane is scrolled to show it. This appears to be working OK, but I don't know if it's the best it could be. As you can see from the section that's commented out I've tried to use the scrollRectToVisible method of the viewport in the scroll pane but it's not consistently making the correct label visible.
    Thanks in advance for any advice.
    package tester;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.SwingUtilities;
    public class AutoscrollingExample extends JFrame {
         private final int TOTAL_LABELS = 100;
         // Keeps track of label for int value in left box
         private Map<Integer, JLabel> labelsInLeftBoxMap = new HashMap<Integer, JLabel>();
         private JScrollPane leftScrollPane;
         public static void main(String[] args) {
              new AutoscrollingExample();
         private AutoscrollingExample() {
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
              splitPane.setLeftComponent(getLeftScrollPane());
              splitPane.setRightComponent(getRightBox());
              splitPane.setDividerLocation(splitPane.getLeftComponent().getPreferredSize().width + 25);
              this.setLayout(new BorderLayout());
              this.add(splitPane, BorderLayout.CENTER);
              this.setLocationByPlatform(true);
              this.setSize(400, 400);
              this.setResizable(false);
              this.setTitle("Scroll Testing");
              this.setVisible(true);
         private Box getRightBox() {
              Box rightBox = Box.createVerticalBox();
              int boxEveryXNumbers = 10;
              Box currentBox = new Box(BoxLayout.LINE_AXIS);
              for(int i=1; i<=TOTAL_LABELS; i++) {
                   JLabel thisLabel;
                   if(i < 10) {
                        thisLabel = new JLabel("  "+i+" ");
                   } else {
                        thisLabel = new JLabel(" "+i+" ");
                   thisLabel.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             handleMouseClickOnLabel(e);
                   currentBox.add(thisLabel);
                   currentBox.add(Box.createHorizontalStrut(5));
                   if(i > 0 && i % boxEveryXNumbers == 0) {
                        rightBox.add(currentBox);
                        rightBox.add(Box.createVerticalStrut(5));
                        currentBox = new Box(BoxLayout.LINE_AXIS);
              rightBox.add(Box.createVerticalGlue());
              return rightBox;
         private JScrollPane getLeftScrollPane() {
              Box leftBox = Box.createVerticalBox();
              for(int i=1; i<=TOTAL_LABELS; i++) {
                   JLabel leftLabel = new JLabel(" "+i+" ");
                   labelsInLeftBoxMap.put(i, leftLabel);
                   leftBox.add(leftLabel);
              leftScrollPane = new JScrollPane();
              leftScrollPane.getViewport().add(leftBox);
              return leftScrollPane;
         private void handleMouseClickOnLabel(MouseEvent e) {
              // Get the int value of clicked label by parsing trimmed text
              JLabel sourceLabelInRightBox = (JLabel) e.getSource();
              int clickedLabelNumber = Integer.parseInt(sourceLabelInRightBox.getText().trim());
              System.out.println("clickedLabelNumber: "+clickedLabelNumber);
              // Highlight the selected label and reset highlight on other labels
              for(Integer oneKey : labelsInLeftBoxMap.keySet()) {
                   if(oneKey.equals(clickedLabelNumber)) {
                        labelsInLeftBoxMap.get(oneKey).setForeground(Color.red);
                   } else {
                        labelsInLeftBoxMap.get(oneKey).setForeground(Color.black);
               * Attempt to scroll the left scroll pane to ensure the selected label
               * is visible
              JLabel labelInLeftComponent = labelsInLeftBoxMap.get(clickedLabelNumber);
              Rectangle leftLabelRectangle = new Rectangle(
                        labelInLeftComponent.getLocation().x,
                        labelInLeftComponent.getLocation().y,
                        labelInLeftComponent.getSize().width,
                        labelInLeftComponent.getSize().height);
              System.out.println(labelInLeftComponent.getLocation());
              if(!SwingUtilities.isRectangleContainingRectangle(leftScrollPane.getViewport().getViewRect(),
                        leftLabelRectangle)) {
                   System.out.println("label isn't visible - attempting to scroll");
                   leftScrollPane.getViewport().setViewPosition(leftLabelRectangle.getLocation());
                   // scrollRectToVisible doesn't consistently scroll so label is visible
                   // leftScrollPane.getViewport().scrollRectToVisible(leftLabelRectangle);
              } else {
                   System.out.println("label is already visible - doing nothing");
    }

    scrollRectToVisible works fine for me (and always has).import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class AutoScrollingExample {
      private final int TOTAL_LABELS = 100;
      private Map<Integer, JLabel> labelsInLeftBoxMap = new HashMap<Integer, JLabel>();
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new AutoScrollingExample().makeUI();
      public void makeUI() {
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(getLeftScrollPane());
        splitPane.setRightComponent(getRightBox());
        splitPane.setDividerLocation(splitPane.getLeftComponent().getPreferredSize().width + 25);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.add(splitPane);
        frame.setVisible(true);
      private Box getRightBox() {
        Box rightBox = Box.createVerticalBox();
        int boxEveryXNumbers = 10;
        Box box = new Box(BoxLayout.LINE_AXIS);
        for (int i = 1; i <= TOTAL_LABELS; i++) {
          JLabel thisLabel = new JLabel(String.format("%3d", i));
          thisLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
              String text = ((JLabel) e.getSource()).getText().trim();
              JLabel target = labelsInLeftBoxMap.get(Integer.parseInt(text));
              ((JComponent) target.getParent()).scrollRectToVisible(target.getBounds());
          box.add(thisLabel);
          box.add(Box.createHorizontalStrut(5));
          if (i > 0 && i % boxEveryXNumbers == 0) {
            rightBox.add(box);
            rightBox.add(Box.createVerticalStrut(5));
            box = new Box(BoxLayout.LINE_AXIS);
        rightBox.add(Box.createVerticalGlue());
        return rightBox;
      private JScrollPane getLeftScrollPane() {
        Box leftBox = Box.createVerticalBox();
        for (int i = 1; i <= TOTAL_LABELS; i++) {
          JLabel leftLabel = new JLabel(" " + i + " ");
          labelsInLeftBoxMap.put(i, leftLabel);
          leftBox.add(leftLabel);
        JScrollPane leftScrollPane = new JScrollPane();
        leftScrollPane.getViewport().add(leftBox);
        return leftScrollPane;
    }db

  • Stop JScrollPane from scrolling

    Hello, I am trying to improve a special editor i have written. Now I tried to add line numbering to it and got stuck. Here's what I did:
    I have a JScrollPane that contains a JPanel. This JPanel has a BorderLayout and contains a JTextPane (where the editable text is) in the CENTER and a JTextArea (containing the line numbers) in the WEST.
    Everytime the text is edited, I count the lines and update the JTextArea so that the right amount of line numbers is shown. But here's the problem: Everytime I update the line numbers, the JScrollPane scrolls down to the very bottom, so in some cases the caret gets hidden (which is very annoying).
    Can someone tell me how I can tell the JScrollPane (or whoever else is to blame for this) not to scroll when I update the line number JTextArea? Is there an easy way to achieve this?
    Thanks in advance

    Another way to do this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    class Test extends JFrame
    public Test()
    super("Test");
    JEditorPane edit = new JEditorPane();
    edit.setEditorKit(new MyRTFEditorKit());
    edit.setEditable(true);
    JScrollPane scroll=new JScrollPane(edit);
    getContentPane().add(scroll);
    setSize(300,300);
    setVisible(true);
    public static void main(String a[])
    new Test();
    class MyRTFEditorKit extends RTFEditorKit
    public ViewFactory getViewFactory()
    return new MyRTFViewFactory();
    class MyRTFViewFactory implements ViewFactory
    public View create(Element elem)
    String kind = elem.getName();
    if (kind != null)
    if (kind.equals(AbstractDocument.ContentElementName)) {
    return new LabelView(elem);
    } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
    // return new ParagraphView(elem);
    return new MyParagraphView(elem);
    } else if (kind.equals(AbstractDocument.SectionElementName)) {
    // return new BoxView(elem, View.Y_AXIS);
    return new MySectionView(elem, View.Y_AXIS);
    } else if (kind.equals(StyleConstants.ComponentElementName)) {
    return new ComponentView(elem);
    } else if (kind.equals(StyleConstants.IconElementName)) {
    return new IconView(elem);
    // default to text display
    return new LabelView(elem);
    class MySectionView extends BoxView {
    public MySectionView(Element e, int axis)
    super(e,axis);
    public void paintChild(Graphics g,Rectangle r,int n) {
    if (n>0) {
    MyParagraphView child=(MyParagraphView)this.getView(n-1);
    int shift=child.shift+child.childCount;
    MyParagraphView current=(MyParagraphView)this.getView(n);
    current.shift=shift;
    super.paintChild(g,r,n);
    class MyParagraphView extends javax.swing.text.ParagraphView
    public int childCount;
    public int shift=0;
    public MyParagraphView(Element e)
    super(e);
    short top=0;
    short left=20;
    short bottom=0;
    short right=0;
    this.setInsets(top,left,bottom,right);
    public void paint(Graphics g, Shape a)
    childCount=this.getViewCount();
    super.paint (g,a);
    int rowCountInThisParagraph=this.getViewCount();
    System.err.println(rowCountInThisParagraph);
    public void paintChild(Graphics g,Rectangle r,int n) {
    super.paintChild(g,r,n);
    g.drawString(Integer.toString(shift+n+1),r.x-20,r.y+r.height-3);

  • JScrollPane - scroll unit too small

    Hi,
    I have a component that must be scrolled inside JScrollPane.
    The problem is that a default scroll unit equals to 1px when I press scroll buttons or attempt to use mouse wheel that makes scrolling very lazy. How to increase scroll unit?
    Anton

    Try this (to use 10 instead of 1):
    yourScrollPane.getVerticalScrollBar().setUnitIncrement(10);
    yourScrollPane.getVerticalScrollBar().setBlockIncrement(10);

  • Can we add same JPanel twice??.. on JFrame and JDialog together!!

    Hello Frnds,
    my problem is quite weird!! i will try to explain..as much as I can !!
    My requirement is I want to show same JPanel in JDialog and JFrame at once..!!
    I am adding a
    JPanel A ---> JDialog
    JPanel A ---> JScrollPanel B
    JScrollPane B ---> JFrame.. and making frame and dialog visible together.. but JPanel is visible in dialog only..
    if i dont add in JDialog.. then JPanel is visible in frame.. !!.. but why that??
    JFrame fr = new JFrame();
    JPanel np = new JPanel();      // This JPanel is added Twice
    np.setBounds(0, 0, 128, 128);
    JScrollPane scroll=new JScrollPane(np);      // Once JPanel added here..
    scroll.setPreferredSize(new Dimension(385,385));
    fr.add(scroll);
    JDialog dlg=new JDialog(fr, "Another Panel", false);
    dlg.add(np);                        // Second Time JPanel added here..
    dlg.pack();
    dlg.setVisible(true);
    fr.setVisible(true);

    Let's make it very clear : it is NOT possible to add
    the same instance of a component to two different
    containers.
    Is it possible to have frame with component.. but on closing that frame component shifts to another frame.. and vice versa I will add to the above:
    it is NOT possible to add the same instance of a component to two different containers... at the same time. Does that clarify it?
    Why is it so hard to try it yourself?
    Instead of waiting a couple of hours hoping someone answers the question you could have solved your problem in a couple of minutes.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • How do you add a scroll bar to a scrolling text field in a folio?

    I've created iPhone and iPad folios with multiple pages. There are scrolling text fields on each page. The fields scroll as designed, but the scroll bars on the  text fields only appear while actually scrolling. Is there a way to have them always visible so the user knows there is more hidden info? The only bars that are constantly visible are the page scroll bars.  Thanks!

    Why is your content pane null? I thought the content pane was the top-level in all windows? If you want complete control over the location of a list box, you want to set the layout of the content pane to null... the way I almost always do this is the other way around, to create my own panel and use setContentPane instead:
    JPanel content = new JPanel(null);
    JScrollPane scroll = new JScrollPane(myListBox);
    scroll.setBounds(380, 10, 500, 500);
    content.add(scroll);
    setContentPane(content);

  • Word wrap with JScrollPane

    Quick question. Trying to get word wrap in a JTextField
    using JSrollPane. Below is a small snippet of code
    from my program...
    displayArea = new JTextArea ( );
    JScrollPane scroll = new JScrollPane ( displayArea,
       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
       JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); Doesn't using JScrollPane.HORIZONTAL_SCROLLBAR_NEVER automatically
    introduce word wrap? I'm not getting it in my program. Somebody please correct me. Thanks!

    displayArea.setLineWrap (true);
    displayArea.setWrapStyleWord (true);I thought it wasn't added automatic.
    Kind regards,
      Levi

  • Need help fast :a question about jcomponent and jscrollpane

    I draw a graphic on a jcomponent like this :
    class drawrecttree extends JComponent {
    public void paint( Graphics g) {
    and I add this to jscrollpane:
    drawrecttree www=new drawrecttree();
    www.k_choose=k_valuenow;
    www.node=currentNode;
    www.setAutoscrolls(true);
    jScrollPane2.setViewportView(www);
    but I hope the jscrollpane can autoscroll,that means jscrollpane's size is 400*400,if the Jcomponent's size is 200*300, just add jcomponent;if jcomponent is bigger than 400*400,the jscrollpane can autoscroll,how can I do that?
    Edited by: hcgerard on Jan 8, 2008 2:18 AM
    Edited by: hcgerard on Jan 8, 2008 2:22 AM
    Edited by: hcgerard on Jan 8, 2008 2:52 AM

    Below is a small non-compilable unit (you need to add a few things of course) - but at any rate, here is some code that, if you get it working, you will see that the scrollbars do the right thing.
    public class TestScrollPane  extends JFrame {
      private Container     container;
      private JPanel        panel;
      private JLabel        label;
      private JScrollPane   scroller;
      public TestScrollPane() {
        container = getContentPane();
        panel     = new JPanel();
        panel.setLayout(new BorderLayout());
        /* Get you images here ...                */
        /* I will call them imageOne and imageTwo */
        label     = new JLabel(new ImageIcon(imageOne));
        panel.add(label);
        scroller  = new JScrollPane(panel);
        scroller.setPreferredSize(new Dimension(100, 100));
        container.add(scroller);
        pack();
        /* Rest of JFrame stuff */
      public static void main(String[] argv)  throws InterruptedException {
        TestScrollPane tsp = new TestScrollPane();
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageTwo));
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageOne));
    }

  • Horizontal Scroll Bar does not show

    I have a method which creates a table with values and displays it in a dialog. However, the horizontal scroll bars do not appear, even though there is are columns that are not seen in the view. Here is my code:
         private void setTable()
              Object columns[] = headerLST.toArray(),
                        rows[][] = new Object[rowLST.size()][headerLST.size()];     
              for(int x = 0; x < rowLST.size(); x++)
                   java.util.List list1 = (java.util.List)rowLST.get(x);
                   for(int y = 0; y < list1.size(); y++)
                        rows[x][y] = (String)list1.get(y);     
              DefaultTableModel tValues = new DefaultTableModel(rows, columns);
    JTable tableA = new JTable(tValues);
         tableA.setRowHeight(27);
                   tableA.setRowSelectionAllowed(false);
                   tableA.setColumnSelectionAllowed(false);
                   tableA.setFont(new Font("Dialog", Font.BOLD, 12));
              int minColWidth = 120, maxColWidth = 200;
              for(int y = 0; y < tableA.getColumnCount(); y++)
                   TableColumn tbc = tableA.getColumnModel().getColumn(y);
                   tbc.setPreferredWidth(minColWidth);     
                   tbc.setMinWidth(minColWidth);
                   tbc.setMaxWidth(maxColWidth);
              scrollA = new JScrollPane(tableA);
              this.getContentPane().add(scrollA, BorderLayout.CENTER);
    Can someone tell me what I am missing?
    Thanks
    Augustine

    You need this
    tableA.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    otherwise it will always try and fit the table to the space available

Maybe you are looking for

  • Suspend resume fail - nvidia 8600gt

    When resuming, shows kernel message like '...soft reset failed...' short time. screen goes black. power button works. I've tried with, linux, nouveau linux, nvidia linux-lts, nvidia-lts Any advice will be appreciated. Thanks. $ sudo lspci -vvv -s 01:

  • Change the Finder search default to Find by Name (search by file name) rather than Find by Content

    I just discovered another way to set the finder Find option to default to "find by name" (search by file name). I'm using Mac OS X 10.8.5 Mountain Lion. I'm not sure if this works on other OS versions, but it probably does. Here's a step by step: #1:

  • Adhoc Query Issue - How to restrict /SAPQUERY/H2 access

    Hi Experts, I have created two User Groups HR_1 (assigned to infosets for Time data) and HR_2 (assigned to Infosets for Payroll data). Also, I want to assign the HR_1 to a user Time_admin and HR_2 to Payroll_Admin, so that Payroll admin do not have a

  • ERROR WHILE COMPLING CLIENT

    I am not ablr to complie client bean, i have created 2 directories beans,client under beans dir i have put home,remote,bean classes. named it as beans package. in client directory i am refering this classes by importing the beans package, but it give

  • Flash Player 9 won't install

    I downloaded the install_flash_player.exe, I opened it, it unpacks and then it goes away not finishing the installation. There isn't anything in the task manager saying that it is still working. It installs and works fine in IE via the web; it won't