JScrollPan

Hi. I'm new to swing so I have a couple questions.
1) When adding a JScrollPane to a JFrame how do you control the size of the JScrollPane?
2) How do you remove the ability to resize from a JFrame.

JScrollPane scrollPane = new JScrollPane();
scrollPane.setSize(dimension);
scrollPane.setPreferredSize(dimension);
or it will automatically resize to whatever component you have inside it.
Use a JDialog instead, and setResizable(false); Don't know off hand how to prevent resizing of JFrame.

Similar Messages

  • How to add a JScrollPane in a JPanel

    I have a JPanel (layout = null, size = 200*400).
    I would like to add a JScrollPane, that sizes 100*100 and that contains an other JPanel, at the location 0,200 in the first JPanel. I would like too that the JScrollBar is always visible.
    How is it possible ?

    The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scroll pane. So you probably need to add:
    panel.setPreferredSize(...);
    Of course if you use LayoutManagers, instead of a null layout, then this is done automatically for you.
    If you want the scroll bars to appear all the time then read the JScrollPane API.

  • How to repaint a JTextArea inside a JScrollPane

    I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
    The following code doesnt run correctly.
    ((JTextArea)Destino).append('\n' + Mens);
    Destino.revalidate();
    Destino.paint(Destino.getGraphics());
    I tried also:
    Destino.repaint();
    Thanks a lot in advance

    Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
    If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Design problem with JScrollPane

    First, I have problems with english. I hope u understand without problems that Im trying to say here. Sorry about that.
    Mi problem is whit a JScrollPane. I want to put an image whit a predefined size for draw inside it. I dont have any information about it, just the size. I want to put it in a JPane. The best choice is use the JPane area. The problem is that I want to use a JScrollPane because the image is bigger that the visualization area.
    Im unable to put a Canvas in the ScrollPane, or a JPane whit a predefined size or an image whit a predefined size. Im sure that is a design problem. Somebody can tell me something I can start whit? What do u think is better choice to put inside a JScrollPane?
    I dont send any source code because I dont have anything else that is show in the example.
    Gracias.

    import java.awt.*;
    import javax.swing.*;
    import java.net.URL;
    public class Test extends JFrame {
      String url = "http://www.sandbox-usa.com/images/product_images/2piece_16.gif";
      public Test() {
    //    System.getProperties().put( "proxySet", "true" );  // uncomment if you have proxy
    //    System.getProperties().put( "proxyHost", "myproxy.mydomain.com" ); // Your proxyname/IP
    //    System.getProperties().put( "proxyPort", "80"); // Sometimes 8080   
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        Container content = getContentPane();
        try {
          Image i = Toolkit.getDefaultToolkit().getImage(new URL(url));
          JLabel jl = new JLabel(new ImageIcon(i));
          content.add(new JScrollPane(jl), BorderLayout.CENTER);
          setSize(200, 200);   
          setVisible(true); 
        } catch (Exception e) { e.printStackTrace(); }
      public static void main(String[] args) { new Test(); }
    }

  • Zooming an image and scrolling it using a JScrollPane

    Hi all, I know this is one of the most common problems in this forum but i cant get any of the replys to work in my code.
    The problem:
    I create an image with varying pixel colors depending on the value obtained from an AbstractTableModel and display it to the screen.
    I then wish to be able to zoom in on the image and make it scrollable as required.
    At the minute the scrolling method is working but only when i resize or un-focus and re-focus the JInternalFrame. Ive tried calling revalidate (and various other options) on the JScrollPane within the paintComponents(Graphics g) method but all to no avail.
    Has anyone out there any ideas cause this is melting my head!
    Heres the code im using (instance is called and added to a JDesktopPane):
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.AffineTransform;
    import uk.ac.qub.mvda.gui.MVDATableModel;
    import uk.ac.qub.mvda.utils.MVDAConstants;
    public class HCLSpectrumPlot extends JInternalFrame implements MVDAConstants
      AbstractAction zoomInAction = new ZoomInAction();
      AbstractAction zoomOutAction = new ZoomOutAction();
      double zoomFactorX = 1.0;
      double zoomFactorY = 1.0;
      private AffineTransform theTransform;
      private ImagePanel imageViewerPanel;
      private JScrollPane imageViewerScroller;
      public HCLSpectrumPlot(String title, MVDATableModel model)
        super(title, true, true, true, true);
        int imageHeight_numOfRows = model.getRowCount();
        int imageWidth_numOfCols = model.getColumnCount();
        int numberOfColourBands = 3;
        double maxValueInTable = 0;
        double[][] ValueAtTablePosition =
            new double[imageHeight_numOfRows][imageWidth_numOfCols];
        for(int i=0; i<imageHeight_numOfRows; i++)
          for(int j=0; j<imageWidth_numOfCols; j++)
         ValueAtTablePosition[i][j] = ((Double)model.getValueAt
                 (i,j)).doubleValue();
        for(int i=0; i<imageHeight_numOfRows; i++)
          for(int j=0; j<imageWidth_numOfCols; j++)
         if ( ValueAtTablePosition[i][j] > maxValueInTable)
           maxValueInTable = ValueAtTablePosition[i][j];
        BufferedImage newImage = new BufferedImage(imageWidth_numOfCols,
              imageHeight_numOfRows, BufferedImage.TYPE_3BYTE_BGR);
        WritableRaster newWritableImage = newImage.getRaster();
        int colourB;
        double pixelValue, cellValue, newPixelValue;
        for (int x = 0; x < imageHeight_numOfRows; x++)
          for (int y = 0; y < imageWidth_numOfCols; y++)
         colourB = 0;
         cellValue = ValueAtTablePosition[x][y];
         pixelValue = (1 - (cellValue / maxValueInTable)) * 767;
         pixelValue = pixelValue - 256;
         while (colourB < numberOfColourBands)
           if ( pixelValue < 0 )
             newPixelValue = 256 + pixelValue;
             newWritableImage.setSample(x, y, colourB, newPixelValue);
             colourB++;
                while ( colourB < numberOfColourBands )
               newWritableImage.setSample(x, y, colourB, 0);
               colourB++;
         else
           newWritableImage.setSample(x, y, colourB, 255);
         colourB++;
         pixelValue = pixelValue - 256;
          }//while
         }//for-y
        }//for-x
        imageViewerPanel = new ImagePanel(this, newImage);
        imageViewerScroller =     new JScrollPane(imageViewerPanel,
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(imageViewerScroller, BorderLayout.CENTER);
        JToolBar editTools = new JToolBar();
        editTools.setOrientation(JToolBar.VERTICAL);
        editTools.add(zoomInAction);
        editTools.add(zoomOutAction);
        this.getContentPane().add(editTools, BorderLayout.WEST);
        this.setVisible(true);
      class ImagePanel extends JPanel
        private int iWidth, iHeight;
        private int i=0;
        private BufferedImage bufferedImageToDisplay;
        private JInternalFrame parentFrame;
        public ImagePanel(JInternalFrame parent, BufferedImage image)
          super();
          parentFrame = parent;
          bufferedImageToDisplay = image;
          iWidth = bufferedImageToDisplay.getWidth();
          iHeight = bufferedImageToDisplay.getHeight();
          theTransform = new AffineTransform();
          //theTransform.setToScale(parent.getContentPane().getWidth(),
                                    parent.getContentPane().getHeight());
          this.setPreferredSize(new Dimension(iWidth, iHeight));
        }//Constructor
        public void paintComponent(Graphics g)
          super.paintComponent(g);
          ((Graphics2D)g).drawRenderedImage(bufferedImageToDisplay,
                                             theTransform);
          this.setPreferredSize(new Dimension((int)(iWidth*zoomFactorX),
                                          (int)(iHeight*zoomFactorY)));
        }//paintComponent
      }// end class ImagePanel
       * Class to handle a zoom in event
       * @author Ross McCaughrain
       * @version 1.0
      class ZoomInAction extends AbstractAction
       * Default Constructor.
      public ZoomInAction()
        super(null, new ImageIcon(HCLSpectrumPlot.class.getResource("../"+
                  MVDAConstants.PATH_TO_IMAGES + "ZoomIn24.gif")));
        this.putValue(Action.SHORT_DESCRIPTION,"Zooms In on the Image");
        this.setEnabled(true);
      public void actionPerformed(ActionEvent e)
        zoomFactorX += 0.5;
        zoomFactorY += 0.5;
        theTransform = AffineTransform.getScaleInstance(zoomFactorX,
                                                    zoomFactorY);
        repaint();
      // ZoomOut to be implemented
    }// end class HCLSpectrumPlotAll/any help greatly appreciated! thanks for your time.
    RossMcC

    Small mistake, the revalidate must be called on the panel not on the jsp.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class UsaZ extends JFrame 
         IPanel      panel = new IPanel();
         JScrollPane jsp   = new JScrollPane(panel);
    public UsaZ() 
         addWindowListener(new WindowAdapter()
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setBackground(Color.lightGray);
         getContentPane().add("Center",jsp);
         setBounds(1,1,400,320);
         setVisible(true);
    public class IPanel extends JComponent
         Image  map;
         double zoom = 1;
         double iw;
         double ih;
    public IPanel()
         map = getToolkit().createImage("us.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try {tracker.waitForID(0);}
         catch (InterruptedException e){}
         iw = map.getWidth(this);
         ih = map.getHeight(this);
         zoom(0);     
         addMouseListener(new MouseAdapter()     
         {     public void mouseReleased(MouseEvent m)
                   zoom(0.04);               
                   repaint();      
                   revalidate();
    public void zoom(double z)
         zoom = zoom + z;
         setPreferredSize(new Dimension((int)(iw*zoom)+2,(int)(ih*zoom)+2));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.scale(zoom,zoom);
         g2.drawImage(map,1,1,null);
         g.drawRect(0,0,map.getWidth(this)+1,map.getHeight(this)+1);
    public static void main (String[] args) 
          new UsaZ();
    [/cdoe]
    Noah                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem with JScrollPane and Mouse Event in JDK 1.4

    The folowing code works fine with JDK 1.3. But not with JDK 1.4. It has got a JPanel(main panel) which hosts JScrollPane which hosts another JPanel (drawing Panel). If I remove(do not add) JScrollPane to the main Panel and ad drawing panel directly to the main panel, it works.
    Thanks.
    In order to replicate the exact scenario, I have modified Sun's tutorial ScrollDemo2.java
    * This code is based on an example provided by John Vella,
    * a tutorial reader.
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class ScrollDemo2 extends JPanel {
    private Dimension size; // indicates size taken up by graphics
    private Vector objects; // rectangular coordinates used to draw graphics
    private final Color colors[] = {
    Color.red, Color.blue, Color.green, Color.orange,
    Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
    private final int color_n = colors.length;
    JPanel drawingArea;
    public ScrollDemo2() {
    setOpaque(true);
    size = new Dimension(0,0);
    objects = 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);
    class MyScrollPane extends JScrollPane
    MyScrollPane(JPanel drawingArea)
    super(drawingArea);
    public void grabFocus()
    super.grabFocus();
    public void requestFocus()
    super.requestFocus();
    protected void processFocusEvent(FocusEvent e)
    if ( e.getID() == FocusEvent.FOCUS_GAINED )
    int i = 0;
    else
    if( e.getID() == FocusEvent.FOCUS_LOST )
    int i = 0;
    super.processFocusEvent(e);
    //Set up the drawing area.
    drawingArea = new JPanel() {
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Rectangle rect;
    for (int i = 0; i < objects.size(); i++) {
    rect = (Rectangle)objects.elementAt(i);
    g.setColor(colors[(i % color_n)]);
    g.fillOval(rect.x, rect.y, rect.width, rect.height);
    g.drawString("Hello",100,100);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    drawingArea.setBackground(Color.LIGHT_GRAY);
    addMouseListener(new MyMouseListener());
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new MyScrollPane(drawingArea);
    scroller.setPreferredSize(new Dimension(200,200));
    setLayout(new BorderLayout());
    add(scroller, BorderLayout.CENTER);
    //If the above line is commented and the line bellow will be uncommented it works.
    //add(drawingArea, BorderLayout.CENTER);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    class MyMouseListener extends MouseInputAdapter {
    final int W = 100;
    final int H = 100;
    public void mouseReleased(MouseEvent e) {
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    // This will clear the graphic objects.
    objects.removeAllElements();
    size.width=0;
    size.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;
    Rectangle rect = new Rectangle(x, y, W, H);
    objects.addElement(rect);
    drawingArea.scrollRectToVisible(rect);
    int this_width = (x + W + 2);
    if (this_width > size.width)
    {size.width = this_width; changed=true;}
    int this_height = (y + H + 2);
    if (this_height > size.height)
    {size.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).
    drawingArea.setPreferredSize(size);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingArea.revalidate();
    drawingArea.repaint();
    public static void main (String args[]) {
    JFrame frame = new JFrame("ScrollDemo2");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setContentPane(new ScrollDemo2());
    frame.pack();
    frame.setVisible(true);

    I tried it . It didn't work.
    Thanks for the suggestionI've got it... I know that inside the paitComponet method you can't call setSize() in jdk1.4, but you could in previous versions... that has caused al lot of problems to me...
    Abraham

  • Problem with JPanel inside JScrollPane

    I want to make a simple graphic editor (like MS-Paint) with Java.
    I create the frame using JFrame, and use many Swing component. But I found
    some difficult when I tried to create the drawing area (the area where user
    performs drawing). I use JPanel as drawing area and I put it in JScrollPane.
    I use JScrollPane in case if user want to create a big drawing area.
    What I want to do with drawing area is, to put it in JScrollPane with size smaller than JScrollPane but I can't get it because the size of drawing area (JPanel) is always be the same as JScrollPane size. In MS-Paint you can see that the canvas (drawing area) size is able to be resize. And the canvas default color is white, and the Scroll Box around it has darkgray color. How can I make it like that (MS-Paint)? Please help. Thanks...
    Irfin

    I haven't actually tested this, but I think it should work...
    Add a JPanel to the scrollpane setting it's background to grey (i think the dark grey in MSPaint is something easy like 128,128,128). Set the layout on that panel to null, then add a second panel to that panel, at freeze it's size (ie. setMaximumSize). Doing it this way will allow you to set like a (10,10) position or something like that, giving the second panel a position away from the edge of the scrollpane.
    Seeing as you will be using mouse listeners anyways, you might even be able to allow for the second panel to be resized by checking the mouse position to see if the mouse is over the edge of the panel. I won't go into detail, that'll ruin the fun for you.
    Good luck, hope this helps.
    Grant.

  • Problem with JPanel in a JScrollPane

    Hi all,
    I am devloping an application where in i insert the JPanel's object in the JScrollPane object. Intitially the size of the JPanel's object is more than the size of the JScrollPane object.At this point fo time i can drag the nob of the scrollpane to the extent of the size of the JPanel's object. Now When i move the mouse behond the size of the JPanel i am increasing the size of the JPanel's object but i cant move the nob of the scrollpane object behond the original limit.
    For example : when you open a notepad there will be scrollbar without the nob if you keep on pressing the enter key the size of the text area increases and we can see the scroll bar now. I what the similar functionality but
    instead of TextArea i need the panel.
    If any of you have solved this problem or know the solution please do inform. I need to solve this problem very urgently. Please do help me out.
    Thanks in Advance.
    regards
    Ravi

    Hi all,
    I got the solution.we need to revalidate the panel object.
    i.e JPanel.revalidate()
    regards
    Ravi Kumar

  • Problem with JPanel and JScrollPane

    Hey,
    I have a class which extends JPanel. Inside this class I would like to have a JScrollPane.
    However, it does not seem to work.
    public class Summary extends JPanel
         JScrollPane scrollPane;
         JPanel p;
         public Summary()
              p = new JPanel()
                          public void paintComponent(Graphics g)
                                 /// do painting here!!!!
              setLayout(null);
              setBorder(BorderFactory.createLineBorder(Color.green));
              setBounds(0,0,240,290);
              //p.setLayout(null);
              p.setLayout(new FlowLayout());
              p.setBorder(BorderFactory.createLineBorder(Color.black));
              //p.setBounds(0,0,240,590);
              p.setPreferredSize(new Dimension(240,500));
              p.add(new JButton("test"));
              scrollPane = new JScrollPane(p);
              scrollPane.setLayout(null);
              scrollPane.setBounds(0,0,240,290);
              scrollPane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
              add(scrollPane);
         }Any advice????
    thanks in advance

    Any advice????ditch this
    setLayout(null);

  • Problem with display of JScrollPane

    I have made a small GUI.
    It has a JFrame and four JPanels are added to the frame.
    The placement is done by program and hence layout manager is set to null.
    Two of the panels contain JScrollPane.
    One scroll pane is associated with a JList.
    Another scroll pane is associated with a JTextArea.
    I am creating panel components in their respective paintComponent() method.
    Now my problem is whenever I run the code, the behaviour of the display of the GUI is erratic. Sometimes it appears perfectly fine other times the JList contents and JTextArea along with their scroll bars don't appear. I have tried running the code on different platforms and different systems. On some systems it works perfectly fine, on some it behaves erratically.
    Moreover my experience is that it is giving problem on somewhat lower configuration systems (low RAM and CPU) and running fine on higher configuration systems.
    I ran it on my laptop with 512MB RAM and centrino duo processor. (Both on windows and ubuntu it gave the same problem, random display behavior)
    I ran it on a desktop with 1GB RAM and higher processor (Both on windows and ubuntu it displayed fine)
    Does this problem relate to insufficient painting time or something of this sort? Why is this problem is coming and what's the solution?
    Thanks in advance.
    Also if anybody has encountered similar problem please do share so that I could at least say this is not a unique one.

    The placement is done by program and hence layout manager is set to null.That is (probably) your first problem. Learn to use use LayoutMangers, they save time in the long run.
    Sometimes it appears perfectly fine other times the JList contents and JTextArea along with their scroll bars don't appearProbably because preferred sizes are not set correctly. Since you are not using a layout manager that is your responsibility. Easy solution is to use a proper combination of layout managers.
    I am creating panel components in their respective paintComponent() method.That is (probably) your second problem. paintComponent() is for doing custom painting, not creating new components dynamically.
    I suggest you start by reading the Swing tutorial for example programs.

  • Problem with JTable in a JScrollPane

    Hello all,
    I have a problem using JTable, that the number of columns is very big,
    and the JScrollPane shows only vertical ScrollBar, isn't there any way to show a horizontal ScrollBar, to show the other columns without being bunched.
    Thanks in advance.

    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

  • How can I add JScrollpane to one of the panels of a JFrame????

    I want to generate a screen with one JFrame and two JPanels.one panel to the left of the Frame and another to the right.
    I want to add a Jscrollpane to left panel,to which i am adding images so that they can be scrolled.How can I achieve this ???????????
    please reply me.............
    this is Basic Frame class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    public class BasicFrame
    private JFrame frame = null;
    private JPanel CanvasPanel = new JPanel();
    private JPanel libraryPanel = null;
    public static void main(String args[])
    new BasicFrame();
    public BasicFrame()
    frame = new JFrame( "Java3d Demo of VRML Loading ");
    frame.setSize( 800, 600 );
    frame.setLayout(new BorderLayout());
         frame.add(CanvasPanel,BorderLayout.EAST);
    frame.add(new LibraryPanel(),BorderLayout.WEST);
         frame.setMenuBar(createMenuBar());
    frame.setVisible( true );
         // kill the window on close
         frame.addWindowListener(new WindowAdapter()
         public void windowClosing(WindowEvent winEvent)
         System.exit(0);
    public MenuBar createMenuBar()
    MenuBar menubar = new MenuBar();
         Menu menu;
    Menu subMenu;
    MenuItem menuItem;
    menu = new Menu("File");
    menuItem = new MenuItem("New");
    menu.add(menuItem);
    //menuItem.addActionListener(this);
    menuItem = new MenuItem("Load");
    menu.add(menuItem);
    //menuItem.addActionListener(this);
    subMenu = new Menu("Save");
    menu.add(subMenu);
    menuItem = new MenuItem("VRML97");
    subMenu.add(menuItem);
    //menuItem.addActionListener(this);
    menuItem = new MenuItem("X3D");
    subMenu.add(menuItem);
    //menuItem.addActionListener(this);
    subMenu = new Menu("Print");
    menu.add(subMenu);
    menuItem = new MenuItem("VRML97");
    subMenu.add(menuItem);
    //menuItem.addActionListener(this);
    menuItem = new MenuItem("X3D");
    subMenu.add(menuItem);
    //menuItem.addActionListener(this);
    menuItem = new MenuItem("Quit");
    menu.add(menuItem);
    //menuItem.addActionListener(this);
    menubar.add(menu);
    menu = new Menu("View");
    menuItem = new MenuItem("Reset");
    menu.add(menuItem);
    menuItem.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    menubar.add(menu);
    return menubar;
    this is Library panel class.To this,I want to add Jscrollpane to scroll the images displayed in this panel.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    public class LibraryPanel extends JPanel
    private ArrayList<String> imageList = new ArrayList<String>();
    private ImageIcon imageIcon;
    private JLabel imageLabel[] = new JLabel[100];
    private String path = "small images";
    private JList list;
    LibraryPanel()
    setSize(400, 600);
    setBorder(BorderFactory.createLineBorder(Color.black));
    setLayout(new FlowLayout());
    JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);
    indexFiles();
    for(int imageNo=0;imageNo<imageList.size();imageNo++)
    try
    imageIcon = new ImageIcon(path + "/" + imageList.get(imageNo));
    imageLabel[imageNo] = new JLabel(imageIcon);
    //scrollPane.getViewport().
              add(imageLabel[imageNo]);
    catch (IllegalArgumentException illegalArgEx)
    illegalArgEx.printStackTrace();
         add(comboBox(),FlowLayout.CENTER);
    add(vbar,FlowLayout.CENTER);
    public JComboBox comboBox()
    String[] comboTypes = { "Sachin", "YuvRaj", "Ganguly", "Dravid", "Sehwag", "Dhoni" };
         // Create the combo box, and set 2nd item as Default
         JComboBox comboTypesList = new JComboBox(comboTypes);
         comboTypesList.setSelectedIndex(0);
         return comboTypesList;
    public void indexFiles()
    File dir = new File(path);
    String[] children = dir.list();
    if (children == null)
    System.err.println("Error: The directory doesn't exists!");
    System.exit(1);
    else
    imageList.ensureCapacity(children.length);
    for (int i = 0; i < children.length; i++)
    if(children.endsWith(".jpg"))
    imageList.add(children[i]);
    please reply me

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    public class BasicFrame
        private JFrame frame = null;
        private JPanel CanvasPanel = new JPanel();
        private JPanel libraryPanel = null;
        public static void main(String args[])
            new BasicFrame(); 
        public BasicFrame()
            frame = new JFrame( "Java3d Demo of VRML Loading ");
            frame.setSize( 800, 600 );
            frame.setLayout(new BorderLayout());
         frame.add(CanvasPanel,BorderLayout.EAST);
            frame.add(new LibraryPanel(),BorderLayout.WEST);
         frame.setMenuBar(createMenuBar());
            frame.setVisible( true );
         // kill the window on close
         frame.addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent winEvent)
                 System.exit(0);
        public MenuBar createMenuBar()
            MenuBar menubar = new MenuBar();
         Menu menu;
            Menu subMenu;
            MenuItem menuItem;
            menu = new Menu("File");
            menuItem = new MenuItem("New");
            menu.add(menuItem);
            //menuItem.addActionListener(this);
            menuItem = new MenuItem("Load");
            menu.add(menuItem);
            //menuItem.addActionListener(this);
            subMenu = new Menu("Save");
            menu.add(subMenu);
            menuItem = new MenuItem("VRML97");
            subMenu.add(menuItem);
            //menuItem.addActionListener(this);
            menuItem = new MenuItem("X3D");
            subMenu.add(menuItem);
            //menuItem.addActionListener(this);
            subMenu = new Menu("Print");
            menu.add(subMenu);
            menuItem = new MenuItem("VRML97");
            subMenu.add(menuItem);
            //menuItem.addActionListener(this);
            menuItem = new MenuItem("X3D");
            subMenu.add(menuItem);
            //menuItem.addActionListener(this);
            menuItem = new MenuItem("Quit");
            menu.add(menuItem);
            //menuItem.addActionListener(this);
            menubar.add(menu);
            menu = new Menu("View");
            menuItem = new MenuItem("Reset");
            menu.add(menuItem);
            menuItem.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
            menubar.add(menu);
            return menubar;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    public class LibraryPanel extends JPanel
        private ArrayList<String> imageList = new ArrayList<String>();
        private ImageIcon imageIcon;
        private JLabel imageLabel[] = new JLabel[100];
        private String path = "small images";
        private JList list;
        LibraryPanel()
            setSize(400, 600);
            setBorder(BorderFactory.createLineBorder(Color.black));
            setLayout(new FlowLayout());
            JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);
            indexFiles();
            for(int imageNo=0;imageNo<imageList.size();imageNo++)
                try
                    imageIcon = new ImageIcon(path + "/" + imageList.get(imageNo));
                    imageLabel[imageNo] = new JLabel(imageIcon);
                    //scrollPane.getViewport().
              add(imageLabel[imageNo]);
                catch (IllegalArgumentException illegalArgEx)
                    illegalArgEx.printStackTrace();
         add(comboBox(),FlowLayout.CENTER);
            add(vbar,FlowLayout.CENTER);
        public JComboBox comboBox()
            String[] comboTypes = { "Sachin", "YuvRaj", "Ganguly", "Dravid", "Sehwag", "Dhoni" };
         // Create the combo box, and set 2nd item as Default
         JComboBox comboTypesList = new JComboBox(comboTypes);
         comboTypesList.setSelectedIndex(0);    
         return comboTypesList;
        public void indexFiles()
            File dir = new File(path);
            String[] children = dir.list();
            if (children == null)
                System.err.println("Error: The directory doesn't exists!");
                System.exit(1);
            else
                imageList.ensureCapacity(children.length);
                for (int i = 0; i < children.length; i++)
                    if(children.endsWith(".jpg"))
    imageList.add(children[i]);

  • JScrollPane size problems with horizontal bar

    Hello,
    I have made a panel with some lines of text (JLabels). The panel is contained inside a JScrollPane. When it gets a horizontal scrollbar, the bar hides the bottom-most line of text and you get a vertical scrollbar too.
    How do I get the JScrollPane to add the height of the horizontal scrollbar to its own height if it still fits inside its own maximum height? It is ridiculous when you have like 3 lines of text inside it and you have to scroll it to see the bottom line.
    Thanks,

    Thanks, that solved the problem good enuff for me here. Now I also got another similar problem, at http://forum.java.sun.com/thread.jsp?forum=57&thread=206828. Got any ideas on that :) ?

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem in using JScrollPane

    hiii i am creating an image editor in java...
    here is my code for using scrollpane
      contentpane = getContentPane();
                view  =  new JLabel(new ImageIcon(bufferedImage));
                scrollpane =  new JScrollPane(view,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
                scrollpane.setPreferredSize(new Dimension(800,600));
                contentpane.add(scrollpane);The problem is that the content of viewport does not change...i.e if i apply any effect to an image....after that as soon as i use the scrollbar, the viewport displays the original image!!!
    What is the problem??
    could someone suggest a solution?

    Can you plzz help me with this??...it is very urgent...
    As i am creating an image editor, so the scrollpane must be updated as soon as i apply any effect to it .....
    along with that whenever a user selects a file from FileDialog...then also it must be updated!!!
    I have extended JFrame for my main class.
    //this is the code i have written when user selects a new file...
    contentpane = getContentPane();
    view =  new JLabel(new ImageIcon(bufferedImage));
    view.setVisible(true);
    crollpane =  new                   JScrollPane(view,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
                scrollpane.setPreferredSize(new Dimension(200,200));
                contentpane.add(scrollpane);
    // This is the code for scollpane update
        iicon.setImage(bufferedImage);
          view.setIcon(iicon);
          scrollpane =  new                     JScrollPane(view,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
                scrollpane.setPreferredSize(new Dimension(200,200));
                contentpane.add(scrollpane);
               scrollpane.updateUI();Message was edited by:
    rav_ahj

Maybe you are looking for