Scrolling a JViewport

Hello,
I am using a JScrollPane to display a JTextPane with a StyledDocument containing a bunch of text. I am successfully using DefaultHighlighter to highlight a word in the JTextPane.
I would like to get the JViewPort to scroll down so that the top line is on the same line that contains the highlighted word (similar to the "find" function in a text editor).
Any ideas on how to do this?

textPane.scrollRectToVisible(textPane.modelToView(int));

Similar Messages

  • SetAutoScrolls not being honored in JEditorPane & subclasses.

    From the JavaDocs on this property states that the "component automatically scrolls its contents when dragged (when contained in a component that supports scrolling, like JViewport"
    The problem I have encountered (and been completely unable to find anything to solve it in the forums/google/google groups) is that setting this property to 'false' does nothing.
    What I am trying to do is have a (JEditor/JText)Pane inside of a JScrollPane that will only scroll when the scroll bars are used. This means that when you select text inside of the JEditorPane and drag down to select more text that the JScrollPane does not scroll down.
    This means that the view of the text document is fixed and does not move no matter how you select the text and move the mouse in the application it will not scroll unless you use the scroll bars.
    The problem is it keeps scrolling, even when calling setAutoScroll(false) on EVERY JComponent that is ever instantiated and then explicitly calling it on EVERY JScrollPane.getViewport() in the JVM just to be certain.
    I don't have any sample code to post because it is pretty trivial.
    //Create Editor Pane
    //Set text of editor pane to something really long so you have to scroll
    //add to a JScrollPane
    //show on screen

    Hi shocko,
    Based on my test, the scenerio is as you stated. We can access the profile via inputing c:\users\%username%and can creare and save new file. Although you Prevent access to drives from My Computer, users still have right to save files to their
    user profiles. 
    The easy way to prevent users to save data on a location is set folder redirection policy, redirect users’ desktop to a network share where users don’t have write permission.
    Create a network share on your server, but don’t grant write permission for domain users group.
    Hope this helps!
    Regards,
    Lany Zhang

  • Paint drawing unscrolled graph over scrolled graph! JScrollPane JViewport

    I am planning to create a JScrollPane that has a scrollable JPanel. I have created a special paint method for the JPanel.
    The JPanel contains a simple graph.
    The graph will be scrolled with the JScrollPane.
    evreything is good until now.
    I want to draw (over the JPanel) another graph which I dont want it to be scrolled by the JScrollPane.
    I want: When moving the scrolls, the graph moves but the special graph does not get effected.
    I planned to overrirde the paint method of the JViewport object. I can see that the plan is good and the result is 80% pluasable, however, I am experiencing some effects:
    1- sometimes the special graph does not get painted!
    2- sometimes when moving the scrolls the up and down, the special graph does move, as if the contents are not updated.
    I am using Java 5 update 6!
    Here is my code, please test it your self:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test{
         public static void main(String[]args){
              JFrame f=new JFrame();
              JPanel p=new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        g.setColor(Color.red);
                        for(int i=0;i<4000;i+=20){
                             g.drawLine(0,i,800,i);
              JViewport port=new JViewport(){
                   public void paint(Graphics g){
                        super.paint(g);
                        g.fillRect(0,0,70,70);
              port.setView(p);
              p.setPreferredSize(new Dimension(500,4000));
              JScrollPane pane=new JScrollPane();
              pane.setViewport(port);
              f.add(pane);
              f.pack();
              f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
              f.setVisible(true);
    }

    This makes use of the fact that heavyweight/awt components are rendered over lightweight/swing components. Another way to do this is with a glass pane (JRootPane api). The tutorial has an example of glass pane use.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FloatingControls
        private JPanel getContent()
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.setLayout(overlay);
            panel.add(getControls());
            panel.add(getGraphicComponent());
            return panel;
        private JScrollPane getGraphicComponent()
            JPanel p=new JPanel()
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.red);
                    for(int j=0;j<4000;j+=20)
                        g.drawLine(0,j,800,j);
            p.setPreferredSize(new Dimension(500,4000));
            return new JScrollPane(p);
        private JPanel getControls()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            Panel awtPanel = new Panel(gridbag)
                public void paint(Graphics g)
                    super.paint(g);
                    int w = getWidth();
                    int h = getHeight();
                    g.setColor(Color.blue);
                    g.fillRect(0,0,w-1,2);      // top
                    g.fillRect(0,2,2,h-5);      // left
                    g.fillRect(0,h-3,w-1,2);    // bottom
                    g.fillRect(w-3,2,2,h-5);    // right
                public Dimension getPreferredSize()
                    // beware of different plaf settings
                    return new Dimension(350, 45);
            awtPanel.setBackground(Color.pink);
            for(int j = 0; j < 4; j++)
                awtPanel.add(new JButton("button " + (j+1)), gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setOpaque(false);
            gbc.insets = new Insets(0,5,0,20);
            // an option, works with insets
            //gbc.fill = GridBagConstraints.HORIZONTAL;
            panel.add(awtPanel, gbc);
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new FloatingControls().getContent());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to put graphics into a JViewport?

    Hi,
    I'm trying to make a simple game, where a block can move around in a 30x30 grid with collision detection. So far, it works alright, but I want the window to hold only 10x10 and for the block that is moving to stay at the center while the painted background moves around. The program reads a .dat file to get the world.
    So is there a way to use the background world Ive painted and put it into a viewport so that it will scroll when the keys are hit to move? Also I'd like to make the block stay at the center of the screen, unless it's at a corner.
    Hopefully this makes sense and someone can help. Thanks.
    Here's my code:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.io.*;
    public class SmallWorld extends JPanel
                              implements KeyListener,
                                         ActionListener {
         //WORLD
         String[][] worldArray = new String[30][30];
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,150);
         private static Color blackBlock = new Color(0,0,0,150);
         boolean keyUP = false;
         boolean keyDOWN = false;
         boolean keyLEFT = false;
         boolean keyRIGHT = false;
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         JTextField typingArea;
         JViewport viewable;
        public SmallWorld() {
            super( );
              createWorld();     
            typingArea = new JTextField(20);
            typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              String type = "";
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        type = worldArray[i][j];
                             if ( type.equals("1") )
                                  g.setColor(redBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );
                             else {
                                  g.setColor(whiteBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );          
              g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );     
         //Get the world from the DAT file and translate it into a 2d array to be used by paintComponent
         public void createWorld() {
            String getData = null;
              int countRow = 0;
            try {
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   while ((getData = br.readLine()) != null) {
                  if(countRow < 30) {
                        for (int i = 0; i < 30; i++) {
                             String temp = "" + getData.charAt(i);
                             worldArray[countRow] = temp;
                        countRow++;
    } catch (IOException e) {
    // catch possible io errors from readLine()
    System.out.println("Uh oh, got an IOException error!");
    e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Graphics g = this.getGraphics();
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              if (keyUP) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyDOWN) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyLEFT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyRIGHT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
    //If key typed, put action here. none for now
    public void keyTyped(KeyEvent e) {
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    updateView( e );
    //If key released, put action here. none for now
    public void keyReleased(KeyEvent e) {
    /** Handle the button click. */
    public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP is pressed
              if ( e.getKeyCode() == 38 ) {
                   keyUP = true;
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        this.repaint();
                        moveBlock();
                   keyUP = false;
              //if DOWN is pressed
              if ( e.getKeyCode() == 40 ) {
                   keyDOWN = true;
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        this.repaint();
                        moveBlock();
                   keyDOWN = false;
              //if LEFT is pressed
              if ( e.getKeyCode() == 37 ) {
                   keyLEFT = true;
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        this.repaint();
                        moveBlock();
                   keyLEFT = false;
              //if RIGHT is pressed
              if ( e.getKeyCode() == 39 ) {
                   keyRIGHT = true;
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        this.repaint();
                        moveBlock();
                   keyRIGHT = false;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SmallWorld");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new SmallWorld();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
         frame.setSize(500,520);
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    The world DAT file:
    111111111111111111111111111111
    100010001010001000101000100011
    100010001010001000101000100011
    100011101010000000001000000001
    100010000010000000001000000001
    100110000010000000001000000001
    100000000010000000001000000001
    111100011110000000001000000001
    100000000110001110111000111011
    100000000000001110111000111011
    100000000000000000001000000001
    100010001110000000000000000001
    100010001110001110111000111011
    100011101100000000000000000011
    100010000110001110111000111011
    100110000100000000000000000011
    100000000110000000001000000001
    111100011100000000000000000011
    100000000100000000000000000011
    100000000010000000000000000001
    100000000010000000000000000001
    100010000000000000000000000001
    100010000000001110111000111011
    100011101110000000011000000001
    100010000110000000011000000001
    100110000110000000001000000001
    100000000110001110111000111011
    111100011110000000011000000001
    100000000110000000011000000001
    100000000011111111111111111111

    I know this is an old posting, but I just saw another question similiar to this and I still have my old code lying around that incorporates most of the suggestions made in this posting. So I thought I'd post my code here in case anybody wants to copy/paste the code. You will still need to use the DAT file provide above as well as provide icons to represent the floor and wall.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class SmallWorld extends JPanel implements KeyListener, ActionListener
         //WORLD
         String[][] worldArray = new String[30][30];
         //Block colors
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,255);
         private static Color blackBlock = new Color(0,0,0,150);
         //World images
    //     JLabel wall = new JLabel( new ImageIcon("wall.gif") );
    //     JLabel floor = new JLabel( new ImageIcon("floor.gif") );
         ImageIcon wallIcon = new ImageIcon("dukewavered.gif");
         ImageIcon floorIcon = new ImageIcon("copy16.gif");
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         //Typing area to capture keyEvent
         JTextField typingArea;
         //Viewable area
         JViewport viewable;
         String type = "";
         JLayeredPane layeredPane;
         JPanel worldBack;
         JPanel panel;
         JPanel player;
         Dimension worldSize = new Dimension(1500, 1500);
         public SmallWorld() {
              super( );
              createWorld();
              layeredPane = new JLayeredPane();
              add(layeredPane);
              layeredPane.setPreferredSize( worldSize );
              worldBack = new JPanel();
              layeredPane.add(worldBack, JLayeredPane.DEFAULT_LAYER);
              worldBack.setLayout( new GridLayout(30, 30) );
              worldBack.setPreferredSize( worldSize );
              worldBack.setBounds(0, 0, worldSize.width, worldSize.height);
              worldBack.setBackground( whiteBlock );
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        JPanel square = new JPanel( new BorderLayout() );
                        worldBack.add( square );
                        type = worldArray[i][j];
                        if ( type.equals("1") )
                             square.add( new JLabel(wallIcon) );
                        else
                             square.add( new JLabel(floorIcon) );
              //Draw the player
              player = new JPanel();
              player.setBounds(50, 50, 50, 50);
              player.setBackground( Color.black );
              player.setLocation(50, 50);
              layeredPane.add(player, JLayeredPane.DRAG_LAYER);
              //set where the player starts
    //          panel = (JPanel)worldBack.getComponent( 31 );
    //          panel.add( player );
              //Create the typing area with keyListener, add to window
              typingArea = new JTextField(20);
              typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         //Get the world from the DAT file and translate it into
         //a 2d array to be used by paintComponent
         public void createWorld() {
              String getData = null;
              int countRow = 0;
              try {
                   //Get file
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   //read each line from file, store to 2d array
                   while ((getData = br.readLine()) != null) {
                        if(countRow < 30) {
                             for (int i = 0; i < 30; i++) {
                                  String temp = "" + getData.charAt(i);
                                  worldArray[countRow] = temp;
                        countRow++;
              } catch (IOException e) {
              System.out.println("Uh oh, got an IOException error!");
              e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              int x = Math.max(0, pt.x - 250);
              int y = Math.max(0, pt.y - 250);
              Rectangle r = new Rectangle(x, y, 550, 550);
              scrollRectToVisible( r );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
         public void keyTyped(KeyEvent e) {
         public void keyPressed(KeyEvent e) {
              updateView( e );
              e.consume();
         public void keyReleased(KeyEvent e) {
         public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP
              if ( e.getKeyCode() == 38 ) {
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if DOWN
              if ( e.getKeyCode() == 40 ) {
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if LEFT
              if ( e.getKeyCode() == 37 ) {
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if RIGHT
              if ( e.getKeyCode() == 39 ) {
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SmallWorld");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JComponent newContentPane = new SmallWorld();
              newContentPane.setPreferredSize( new Dimension(1500, 1500) );
              JScrollPane scrollPane = new JScrollPane( newContentPane );
              scrollPane.setPreferredSize( new Dimension(568, 568) );
              frame.getContentPane().add( scrollPane );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setResizable( false );
              //frame.setSize(500,520);
              frame.setVisible( true );
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater( new Runnable() {
                   public void run() {
                        createAndShowGUI();

  • URGENT! Need help with scrolling on a JPanel!

    Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
    So, straight to the problem:
    I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
    What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
    And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
    Code snippets:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class FilterComp extends JPanel {//implements Scrollable {
      protected DefaultMutableTreeNode root;
      protected Image buffer;
      protected int lastW = 0;
      protected int origoX = 0;
      protected final StringBuffer sb = new StringBuffer();
    //  protected int maxUnitIncrement = 1;
      protected JScrollPane scrollpane = new JScrollPane();
       *  Constructor for the FilterComp object
       *@param  scrollpane  Description of the Parameter
      public FilterComp(JScrollPane scrollpane) {
        super();
    //    setPreferredSize(new Dimension(1000, 500));
        this.setBackground(Color.magenta);
    //    setOpaque(false);
        setLayout(
          new BorderLayout() {
            public Dimension preferredLayoutSize(Container cont) {
              return new Dimension(1000, 600);
        this.scrollpane = scrollpane;
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
        scrollpane.getViewport().add( this, null );
    //    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        repaint();
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getSize().width;
        if (w != lastW) {
          buffer = null;
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (root != null) {
          int h = getHeight(root);
          if (buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g3 = (Graphics2D) buffer.getGraphics();
            g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g3.setColor(Color.black);
            g3.setStroke(new BasicStroke(2));
            paint(g3, (w / 2) + origoX, 10, w / 2, root); 
          lastW = w;
          AffineTransform old = g2.getTransform();
          AffineTransform trans = new AffineTransform();
          trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
          g2.setTransform(trans);
          g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
          g2.setTransform(old);
        updateUI();
       *  Description of the Method
       *@param  g  Description of the Parameter
      public void update(Graphics g) {
        // Call paint to reduce flickering
        paint(g);
       *  Description of the Method
       *@param  g2    Description of the Parameter
       *@param  x     Description of the Parameter
       *@param  y     Description of the Parameter
       *@param  w     Description of the Parameter
       *@param  node  Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
        if (node.getChildCount() == 2) {
          DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
          DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
          if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
            String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
            paint(g2, x, y, s);
          } else {
            g2.drawLine(x - (w / 2), y, x + (w / 2), y);
            Font f = g2.getFont();
            g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
            paint(g2, x, y, node.getUserObject().toString());
            g2.setFont(f);
            g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
            g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
            paint(g2, x - (w / 2), y + 40, w / 2, c1);
            paint(g2, x + (w / 2), y + 40, w / 2, c2);
        } else if (node.getChildCount() == 0) {
          paint(g2, x, y, node.getUserObject().toString());
       *  Description of the Method
       *@param  g2  Description of the Parameter
       *@param  x   Description of the Parameter
       *@param  y   Description of the Parameter
       *@param  s   Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, String s) {
        y += 10;
        StringTokenizer st = new StringTokenizer(s, "\\", false);
        if (s.indexOf("'") != -1 && st.countTokens() > 1) {
          int sh = g2.getFontMetrics().getHeight();
          while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (st.hasMoreTokens()) {
              t += "/";
            int sw = g2.getFontMetrics().stringWidth(t);
            g2.drawString(t, x - (sw / 2), y);
            y += sh;
        } else {
          int sw = g2.getFontMetrics().stringWidth(s);
          g2.drawString(s, x - (sw / 2), y);
       *  Sets the root attribute of the FilterComp object
       *@param  root  The new root value
      public void setRoot(DefaultMutableTreeNode root) {
        this.root = root;
        buffer = null;
       *  Gets the root attribute of the FilterComp object
       *@return    The root value
      public DefaultMutableTreeNode getRoot() {
        return root;
       *  Gets the height attribute of the FilterComp object
       *@param  t  Description of the Parameter
       *@return    The height value
      private int getHeight(TreeNode t) {
        int h = 1;
        int c = t.getChildCount();
        if (c > 0) {
          if (c > 1) {
            h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
          } else {
            h += getHeight(t.getChildAt(0));
        return h;
       *  Sets the x attribute of the FilterComp object
       *@param  x  The new x value
      public void setX(int x) {
        origoX = x;
       *  Gets the x attribute of the FilterComp object
       *@return    The x value
      public int getX() {
        return origoX;
       *  Gets the preferredScrollableViewportSize attribute of the FilterComp
       *  object
       *@return    The preferredScrollableViewportSize value
    //  public Dimension getPreferredScrollableViewportSize() {
    //    return getPreferredSize();
       *  Gets the scrollableBlockIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableBlockIncrement value
    //  public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
       *  Gets the scrollableTracksViewportHeight attribute of the FilterComp object
       *@return    The scrollableTracksViewportHeight value
    //  public boolean getScrollableTracksViewportHeight() {
    //    return false;
       *  Gets the scrollableTracksViewportWidth attribute of the FilterComp object
       *@return    The scrollableTracksViewportWidth value
    //  public boolean getScrollableTracksViewportWidth() {
    //    return false;
       *  Gets the scrollableUnitIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableUnitIncrement value
    //  public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
    }

    The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
    I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
    You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
    You could try this approach using an ImageIcon within a JLabel:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JFrame {
         BufferedImage bi;
         Graphics2D g_bi;
         public Test() {
              super("Scroll Test");
              makeImage();
              Container contentPane = getContentPane();
              MyView view = new MyView(new ImageIcon(bi));
              JScrollPane sp = new JScrollPane(view);
              contentPane.add(sp);
              setSize(200, 200);
              setVisible(true);
         private void makeImage() {
              bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
              g_bi = bi.createGraphics();
              g_bi.setColor(Color.white);
              g_bi.fillRect(0,0,320,240);
              g_bi.setColor(Color.black);
              g_bi.drawLine(0,0,320,240);
         public static void main(String args[]) {
              Test test = new Test();
    class MyView extends JLabel {
         ImageIcon icon;
         public MyView(ImageIcon ii) {
              super(ii);
              icon = ii;
         public void paintComponent(Graphics g) {
              g.drawImage(icon.getImage(),0,0,this);
    }Robert Templeton

  • Help with scrolling screen

    I am writing a turn based strategy game in Java but I am unable to make a scrolling screen you can "move" your view of the game board around in.
    I can do every other aspect of the game myself, except for this.
    Examples of this on the internet are only for Applets(My program is a JFrame)
    Can anyone help?

    http://java.sun.com/javase/6/docs/api/javax/swing/JViewport.html
    Edit: Don't even start with the Swing fascist thing George ;-D
    Further edit: Here, i'll keep it neutral. http://help.eclipse.org/help31/index.jsp?topic=/org.eclipse.draw2d.doc.isv/reference/api/org/eclipse/draw2d/Viewport.html
    Message was edited by:
    jGardner

  • JScrollPane Scroll Position

    Tried posting this in the newbie section with no luck....
    I created a class extending a JScrollPane that encompasses a JTextPane. The method below appends some text to the current JTextPane with a certain color (this part works fine). What I am also trying to do is force the JScrollPane to keep focus at the bottom after the append if it was there before the append. Now I am running into trouble.
    The code can determine fine if the scroll pane is at the end, but after the append, it sometimes prematurely puts the pane at the end again; i.e. the method is telling the scroll pane to go to the end before the text pane and/or scroll pane have finished updating their size. Thus, the scroll pane is moved to the bottom, then the text and scroll panes resize, and the scroll pane is no longer at the bottom.
    It seems that this problem occurs when the text appended is multiple lines, in which case it appears that the panes are resized multiple times- the scroll bar is positioned correctly after the first resize, but subsequent resizings sometimes occur after I reposition the scroll bar to the current "end" (which then changes).
    I've tried validating both panes to force them to update before repositioning the scroll bar, but this does not seem to stop the problem (although it may help).
    Does anyone know how to correct this problem? I'm still guessing that something (perhaps the doc?) is not fully updated by the time I reposition the scroll bar. If this is the problem, any suggestions on how to force the document to be updated before playing with these GUI panes? If possible, I prefer not to use a timer or sleep a thread to wait for this updating.
    Of course, if you know of existing methods/settings that help with this, please tell. I didn't manage to find anything in the API's that gave me what I want, but I've been known to overlook things from time to time ;)
    Again, this is a method in a class extending JScrollPane.
    textPane is the JTextPane embedded in the scroll pane.
    doc is the JTextPane document.
    public synchronized void append(String appendString, Color textColor)
         JScrollBar scrollBar;
         BoundedRangeModel rangeModel;
         boolean isMaxed;
         scrollBar = this.getVerticalScrollBar();
         rangeModel = scrollBar.getModel();
         isMaxed = ((rangeModel.getValue() + rangeModel.getExtent())
                             == rangeModel.getMaximum());
              // check if the scroll bar is at the bottom
         SimpleAttributeSet textAttributes = new SimpleAttributeSet();
         StyleConstants.setForeground(textAttributes, textColor);
         try
              doc.insertString(doc.getLength(), appendString, textAttributes);
              // append the formatted string to the document
         catch(BadLocationException ex)
              System.out.println("Error writing to the text pane");
         if (isMaxed)
              textPane.validate();     //force the text pane to validate
              this.validate();    //force the scroll pane to update
              scrollBar.setValue(rangeModel.getMaximum() - rangeModel.getExtent());
              // The above line is sometimes called before the text and scroll panes
              // have finished updating.  The maximum and extent of the scroll bar
              // depend on the size of the document.

    You are correct in your observation that the size of the JScrollPane is incorrectly reflected for the size of your newly appended document. I spent some time on this bug and eventually came up with the following solution:
    textPane.addComponentListener( new ComponentListener(){
    public void componentHidden(ComponentEvent e)
    public void componentMoved(ComponentEvent e)
    public void componentResized(ComponentEvent e)
    JViewport vp = scrollPane.getViewport();
    incoming.revalidate();
    Rectangle visRect = vp.getViewRect();
    Dimension viewDim = vp.getViewSize();
    Rectangle rect = new Rectangle( 0, (int)(viewDim.getHeight() - visRect.getHeight()),
    (int)visRect.getWidth(), (int)visRect.getHeight() );
    vp.scrollRectToVisible( rect );
    public void componentShown(ComponentEvent e )
    This solution also has the side benefit of scrolling to the bottom when the JTextPane is resized by the user.

  • Swing bug?: scrolling BLIT_SCROLL_MODE painting JTextArea components hangs

    java version "1.5.0_04"
    Hello,
    When drawing JComponent Text Areas and dynamically scrolling, Java gets confused, gets the shivers and freezes when the viewport cannot get its arms around the canvas. ;)
    Possible problem at JViewport.scrollRectToVisible().
    When painting non-text area components eg. graphics circles, it is ok.
    Have provided example code. This code is based on the ScrollDemo2 example provided in the Sun Java
    Tutorial
    thanks,
    Anil Philip
    juwo LLC
    Usage: run program and repeatedly click the left mouse button near right boundary to create a new JComponent node each time and to force scrolling area to increase in size to the right.
    When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers and hangs.
    The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal application) unpainted sometimes.
    * to show possible bug when in the default BLIT_SCROLL_MODE and with JTextArea components.
    * author: Anil Philip. juwo LLC. http://juwo.com
    * Usage: run program and repeatedly click the left mouse button near right boundary to
    * create a new JComponent node each time and to force scrolling area to increase in size to the right.
    * When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers
    and hangs.
    * The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal
    application)
    * unpainted sometimes.
    * This code is based on the ScrollDemo2 example provided in the Sun Java Tutorial (written by John
    Vella, a tutorial reader).
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    /* ScrollDemo2WithBug.java is a 1.5 application that requires no other files. */
    public class ScrollDemo2WithBug extends JPanel {
    private Dimension area; //indicates area taken up by graphics
    private Vector circles; //coordinates used to draw graphics
    private Vector components;
    private JPanel drawingPane;
    public ScrollDemo2WithBug() {
    super(new BorderLayout());
    area = new Dimension(0, 0);
    circles = new Vector();
    components = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    //Set up the drawing area.
    drawingPane = new DrawingPane();
    drawingPane.setBackground(Color.white);
    drawingPane.setPreferredSize(new Dimension(200, 200));
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new JScrollPane(drawingPane);
    // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
    if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
    System.out.println("BACKINGSTORE_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
    System.out.println("BLIT_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
    System.out.println("SIMPLE_SCROLL_MODE");
    //Lay out this demo.
    add(instructionPanel, BorderLayout.PAGE_START);
    add(scroller, BorderLayout.CENTER);
    /** The component inside the scroll pane. */
    public class DrawingPane extends JPanel implements MouseListener {
    private class VisualNode {
    int x = 0;
    int y = 0;
    int id = 0;
    public VisualNode(int id, int x, int y) {
    this.id = id;
    this.x = x;
    this.y = y;
    title.setLineWrap(true);
    title.setAlignmentY(Component.TOP_ALIGNMENT);
    titlePanel.add(new JButton("Hi!"));
    titlePanel.add(title);
    nodePanel.add(titlePanel);
    nodePanel.setBorder(BorderFactory
    .createEtchedBorder(EtchedBorder.RAISED));
    box.add(nodePanel);
    ScrollDemo2WithBug.this.drawingPane.add(box);
    Box box = Box.createVerticalBox();
    Box titlePanel = Box.createHorizontalBox();
    JTextArea title = new JTextArea(1, 10); // 1 rows x 10 cols
    Box nodePanel = Box.createVerticalBox();
    public void paintNode(Graphics g) {
    int ix = (int) x + ScrollDemo2WithBug.this.getInsets().left;
    int iy = (int) y + ScrollDemo2WithBug.this.getInsets().top;
    title.setText(id + " (" + ix + "," + iy + ") ");
    box.setBounds(ix, iy, box.getPreferredSize().width, box
    .getPreferredSize().height);
    int n = 0;
    DrawingPane() {
    this.setLayout(null);
    addMouseListener(this);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fill3DRect(10, 10, 25, 25, true);
    Point point;
    for (int i = 0; i < circles.size(); i++) {
    point = (Point) circles.elementAt(i);
    VisualNode node = (VisualNode) components.get(i);
    node.paintNode(g);
    //Handle mouse events.
    public void mouseReleased(MouseEvent e) {
    final int W = 100;
    final int H = 100;
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    //This will clear the graphic objects.
    circles.removeAllElements();
    area.width = 0;
    area.height = 0;
    changed = true;
    } else {
    int x = e.getX() - W / 2;
    int y = e.getY() - H / 2;
    if (x < 0)
    x = 0;
    if (y < 0)
    y = 0;
    Point point = new Point(x, y);
    VisualNode node = new VisualNode(circles.size(), point.x,
    point.y);
    // add(node);
    components.add(node);
    circles.addElement(point);
    drawingPane.scrollRectToVisible(new Rectangle(x, y, W, H));
    int this_width = (x + W + 2);
    if (this_width > area.width) {
    area.width = this_width;
    changed = true;
    int this_height = (y + H + 2);
    if (this_height > area.height) {
    area.height = this_height;
    changed = true;
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingPane.setPreferredSize(area);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingPane.revalidate();
    drawingPane.repaint();
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ScrollDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ScrollDemo2WithBug();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.setSize(800, 600);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    I changed the name so you can run this as-is without name clashing. It works okay now.
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SD2 extends JPanel {
        public SD2() {
            super(new BorderLayout());
            //Set up the instructions.
            JLabel instructionsLeft = new JLabel(
                    "Click left mouse button to place a circle.");
            JLabel instructionsRight = new JLabel(
                    "Click right mouse button to clear drawing area.");
            JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
            instructionPanel.add(instructionsLeft);
            instructionPanel.add(instructionsRight);
            //Set up the drawing area.
            DrawingPane drawingPane = new DrawingPane(this);
            drawingPane.setBackground(Color.white);
            drawingPane.setPreferredSize(new Dimension(200, 200));
            //Put the drawing area in a scroll pane.
            JScrollPane scroller = new JScrollPane(drawingPane);
            // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
                System.out.println("BACKINGSTORE_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
                System.out.println("BLIT_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
                System.out.println("SIMPLE_SCROLL_MODE");
            //Lay out this demo.
            add(instructionPanel, BorderLayout.PAGE_START);
            add(scroller, BorderLayout.CENTER);
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ScrollDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new SD2();
            newContentPane.setOpaque(true);      //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.setSize(800, 600);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    /** The component inside the scroll pane. */
    class DrawingPane extends JPanel implements MouseListener {
        SD2 sd2;
        private Dimension area;     //indicates area taken up by graphics
        private Vector circles;     //coordinates used to draw graphics
        private Vector components;
        int n = 0;
        final int
            W = 100,
            H = 100;
        DrawingPane(SD2 sd2) {
            this.sd2 = sd2;
            area = new Dimension(0, 0);
            circles = new Vector();
            components = new Vector();
            this.setLayout(null);
            addMouseListener(this);
         * The 'paint' method is a Container method and it passes its
         * Graphics context, g, to each of its Component children which
         * use it to draw themselves into the parent. JComponent overrides
         * this Container 'paint' method and in it calls this method in
         * addition to others - see api. So the children of DrawingPane will
         * each paint themselves. Here you can do custom painting/rendering.
         * But this is not the place to ask components to paint themselves.
         * That would get swing very confused...
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fill3DRect(10, 10, 25, 25, true);
            g.setColor(Color.red);
            Point point;
            for (int i = 0; i < circles.size(); i++) {
                point = (Point) circles.elementAt(i);
                g.fillOval(point.x-2, point.y-2, 4, 4);
        //Handle mouse events.
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                //This will clear the graphic objects.
                circles.removeAllElements();
                components.removeAllElements();
                removeAll();                    // to clear the components
                area.width = 0;
                area.height = 0;
                setPreferredSize(area);
                revalidate();
                repaint();
            } else {
                int x = e.getX() - W / 2;
                int y = e.getY() - H / 2;
                if (x < 0)
                    x = 0;
                if (y < 0)
                    y = 0;
                Point point = new Point(x, y);
                VisualNode node = new VisualNode(this, circles.size(), point.x, point.y);
                // add(node);
                components.add(node);       // not needed
                circles.addElement(point);
                checkBoundries(x, y, node);
        private void checkBoundries(int x, int y, VisualNode node) {
            boolean changed = false;
            // since we used the setPreferredSize property to set the size
            // of each box we'll have to use it again to let the JScrollPane
            // know what size we need to show all our child components
            int this_width = (x + node.box.getPreferredSize().width + 2);
            if (this_width > area.width) {
                area.width = this_width;
                changed = true;
            int this_height = (y + node.box.getPreferredSize().height + 2);
            if (this_height > area.height) {
                area.height = this_height;
                changed = true;
            if (changed) {
                //Update client's preferred size because
                //the area taken up by the graphics has
                //gotten larger or smaller (if cleared).
                setPreferredSize(area);
                scrollRectToVisible(new Rectangle(x, y, W, H));
                //Let the scroll pane know to update itself
                //and its scrollbars.
                revalidate();
            repaint();
        public void mouseReleased(MouseEvent e) { }
        public void mouseClicked(MouseEvent e)  { }
        public void mouseEntered(MouseEvent e)  { }
        public void mouseExited(MouseEvent e)   { }
    * We are adding components to DrawingPanel so there is no need to get
    * into the paint methods of DrawingPane. Components are designed to draw
    * themseleves when their parent container passes them a Graphics context
    * and asks them to paint themselves into the parent.
    class VisualNode {
        DrawingPane drawPane;
        int x;
        int y;
        int id;
        Box box;
        public VisualNode(DrawingPane dp, int id, int x, int y) {
            drawPane = dp;
            this.id = id;
            this.x = x;
            this.y = y;
            box = Box.createVerticalBox();
            Box titlePanel = Box.createHorizontalBox();
            JTextArea title = new JTextArea(1, 10);     // 1 rows x 10 cols
            Box nodePanel = Box.createVerticalBox();
            title.setLineWrap(true);
            title.setAlignmentY(Component.TOP_ALIGNMENT);
            titlePanel.add(new JButton("Hi!"));
            titlePanel.add(title);
            nodePanel.add(titlePanel);
            nodePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
            box.add(nodePanel);
            // here we are adding a component to drawPane so there is really
            // no need to keep this VisualNode in a collection
            drawPane.add(box);
            int ix = (int) x + drawPane.getInsets().left;
            int iy = (int) y + drawPane.getInsets().top;
            title.setText(id + " (" + ix + "," + iy + ") ");
            // since we are using the preferredSize property to setBounds here
            // we'll need access to it (via box) for the scrollPane in DrawPane
            // so we expose box as a member variable
            box.setBounds(ix, iy, box.getPreferredSize().width,
                                  box.getPreferredSize().height);
    }

  • Java.lang.NullPointerException when scrolling in JComboBox

    Hi everybody,
    I use a JComboBox in my application. If I scroll it a NullPointerException is thrown:
    java.lang.NullPointerException
         at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(BufferStrategyPaintManager.java:406)
         at javax.swing.BufferStrategyPaintManager.copyArea(BufferStrategyPaintManager.java:334)
         at javax.swing.RepaintManager.copyArea(RepaintManager.java:1143)
         at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1604)
         at javax.swing.JViewport.windowBlitPaint(JViewport.java:1573)
         at javax.swing.JViewport.setViewPosition(JViewport.java:1118)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:1027)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:1016)
         at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
         at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
         at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
         at javax.swing.JScrollBar.setValue(JScrollBar.java:446)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:962)
         at java.awt.Component.processMouseWheelEvent(Component.java:6126)
         at java.awt.Component.processEvent(Component.java:5810)
         at java.awt.Container.processEvent(Container.java:2058)
         at java.awt.Component.dispatchEventImpl(Component.java:4410)
         at java.awt.Container.dispatchEventImpl(Container.java:2116)
         at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4555)
         at java.awt.Component.dispatchEventImpl(Component.java:4296)
         at java.awt.Container.dispatchEventImpl(Container.java:2116)
         at java.awt.Component.dispatchEvent(Component.java:4240)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4015)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
         at java.awt.Container.dispatchEventImpl(Container.java:2102)
         at java.awt.Window.dispatchEventImpl(Window.java:2429)
         at java.awt.Component.dispatchEvent(Component.java:4240)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)This is the code I execute:
       public static void test()
          Object[] items = new Object[10];
          items[0] = 0;
          items[1] = 1;
          items[2] = 2;
          items[3] = 3;
          items[4] = 4;
          items[5] = 5;
          items[6] = 6;
          items[7] = 7;
          items[8] = 8;
          items[9] = 9;
          JFrame frame = new JFrame("Test frame");
          JPanel panel = new JPanel();
          panel.add(new JLabel("Combobox:"));
          panel.add(new JComboBox(items));
          frame.add(panel);
          frame.pack();
          frame.setVisible(true);
       }The weird thing is that if I execute this piece of code outside my program, in a test class, everything goes fine. I am not sure how this is possible.
    Best regards,
    Jethro Borsje

    You not assign any ActionListener to your ComboBox ?Well, in my real-life implementation I plan to do so, however in the test() method I do not. And the problem is still there in the test method, so to answer your question: no I do not add an ActionListener to the JComoBox in my test case.
    A little bit more info: when I scroll in the JComboBox the scrollwheel of my mouse, the scrollbar on the right side does not move, however the contents of the JComboBox does move.

  • Size of ScrollPane (JViewport)

    I have a JScrollPane that contains a JTextArea.
    When I write more text to the text area the scroll bar appears and that's fine.
    But if I pack() the window the text area gets bigger so that all the text is visible and that's my problem.
    What can I do?
    I tryed setting the size of the JViewport but it didn't work...

    Don't pack() then, it will attempt to resize the components "optimally" which is obiviously not what you're wanting.

  • Creating JScrollPane with vertical scroll only...

    Anyone got any idea how to use a JScrollPane to perform vertical scrolling only?
    The components should be stacked vertically, as wide as the scrollpane and as high as they need to be.
    Is it only possible by adding a ComponentListener to the JScrollPane (or the JViewPort) and setting the maximum width of the components to the width of the viewport?
    Incidentally, anyone know how a JLabel (or any text component) calculates its preferred size when it can wrap the text contained? Ie, how do you get the preferred height for a specified width?

    Doh - implement Scrollable to return true for getScrollableTracksViewportWidth()!

  • Automating scrolling of a JTable when model gets updated

    Hi,
    I have a JTable in a JScrollPane with a table model that updates in real time and I need to keep the currently selected row on the same place on screen (for example when a row is inserted before the selected row I'd like the scroll pane to automatically scroll one row down so the selected row remains at the same location on screen).
    the scrollpane before the row insertion:
    row A
    row B
    row C
    row D (selected)
    row E
    now 'row F' is inserted between B and C
    row B
    row F
    row C
    row D (selected)
    row E
    (row A is scrolled out of sigth and D remains (visually) the 4th row in the view)
    Is there any easy way how to achieve this ? I tried a number of approaches but all end up with an annoying scrollpane jitter.

    I'd try to call JViewPort's scrollRectToVisible(Rectangle contentRect) for the JScrollPane.getViewPort() and keep the parameter Rectangle's size the same (JViewPort.getViewRect()) but adjust the y-position by amount returned by JTable.getRowHeight() + JTable.getRowmargin(). This would be done after row wuold be added and only if vertical scrollbar is visible.
    Maybe this is what you have tried already. Anyway I hope this helps.

  • How to scroll JList to bottom

    I have a JList on a JScrollPane, and it updates in real-time.
    As the data fills the pane, I want it to scroll to the bottom all the time,
    but it stays at the top. I update as follows:
    String voltString[]=new String[someNumber];
    // Set the strings to stuff--code omitted
    voltList.setListData(voltStrings);
    voltList.ensureIndexIsVisible(voltStrings.length);But it doesn't work. The API for ensureIndexIsVisible says something
    about a JViewPort, but I am not sure what it means--I have it on a
    JScrollPane, not a JViewPort.

    works OK like this
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing extends JFrame
      int counter = 0;
      javax.swing.Timer timer;
      public Testing()
        setLocation(200,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final DefaultListModel lm = new DefaultListModel();
        final JList list = new JList(lm);
        JScrollPane sp = new JScrollPane(list);
        sp.setPreferredSize(new Dimension(100,150));
        getContentPane().add(sp);
        pack();
        setVisible(true);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            lm.addElement(counter);
            counter++;
            list.ensureIndexIsVisible(lm.size()-1);
            if(counter > 100) timer.stop();}};
        timer = new javax.swing.Timer(100,al);
        timer.start();
      public static void main(String[] args){new Testing();}
    }

  • How can I know the size of a JViewport laid out in BorderLayout.CENTER?

    I have a JPanel inside a JScrollPane. The scroll pane is laid out inside of BorderLayout.CENTER. I need to know the size of the JViewport to do stuff like centering and zooming.
    Where can I find the size? All these methods return 0 values for X and Y:
    myScrollPane.getViewport().getSize()
    myScrollPane().getSize()
    myScrollPane.getHorizontalScrollbar().getValue()
    Yes, even the scrollbars won't give me any values! It's all because of the BorderLayout!
    Any ideas? Thanks.

    Sounds like you are accessing the sizes before the views are realized (that is before a call to frame.pack()/show()) They are available only after the layoutManager had a go on it. What is available earlier are preferred/min/max, though.
    Greetings
    Jeanette

Maybe you are looking for

  • IPod won't charge correctly

    once my iPod's battery is completely drained I connect it to my computer to charge it. It just sits on the screen with the apple logo and will not charge. (It does this on more than one computer too). If I unplug it after letting it sit for 10-15 min

  • Are there solutions to Compatibility Issues with Thunderbird, Windows 8.1 and Anti-Virus Software, e.g., MacAfee?

    Since I upgraded to Windows 8.1, Thunderbird freezes up and goes into "Not Responding" mode repeatedly every few minutes. My research indicates that it is a problem with compatibility with antivirus software, which obviously is needed with an e-mail

  • Ipod just generally not workin

    This morning I decided to charge my IPOD so plugged IPOD in to USB, no response. So checked if it was on My Computer, not on My Computer, was already in a stressed mood as I had been ill the night before. So started wiggling the IPOD around in the US

  • SolutionDatabase : Not able to Select and attach Solutions in the Message

    Dear Experts, 1.I Have Configured the TREX Search Engine. 2.I Have Configured SAF 3.I Have Done the Basic Settings of SDB 4.I Have Compiled all the Solutions and Problems            When i am opening a Message and View the Solutions in the SDB tab ,

  • Dynamic Imagelink Component - Calling Impl method with input parameter

    Hi All, I have requirement where Imagelinks are created dynamically on the pageload. Generated the components and the components are displayed on the jspx. Now when I click the image link, a method in AMImpl should invoke and this method takes some i