Use of JScrollPane

I try to use the JScrollPane class with a JPanel, which at the time contains a class compounded of several textboxes and other JComponent subclasses.
I am not using any layout manager (setting every layout manager to null), and though displaying the components properly inside the JFrame, I don't get the JScrollPane (or the JViewPort in it) to recognize the underlying size of the JPanel, therefore not displaying any scrollbars, horizontal or vertical, when setting the JScrollPane horizontal and vertical scrollbar policies to "as needed". First guess, is that I should set some of the JScrollPane properties manually, such as extent, min, max and so on. Perhaps the problem lies on the LayoutManager.
The strange point, is that whenever you provide as JViewPort component any root class (such as a texarea), everything works as desired.
Can anybody help? Hope the explanation is clear.
Thanks in advance.
Carlos.

Carlo,
try setting the preferred size of the JScrollPane. If that doesn't work, You'll probably have to put your JScrollPane on another JPanel and set the size of THAT JPanel (the one that holds the scrollpane).
If you just add the JScrollPane onto the JFrame, it will normally take up the whole size of the JFrame.
If you paste up your code, it may help us understand the problem better.

Similar Messages

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • JTable use in JScrollPane

    I have a JTable in JScrollPane which has about 116000 rows of data. I would like to get a status count of what rows are displayed at a time when I move down the scollPane. This is to keep a running track of rows displayed in status message when moving down the scrollpane.
    SAY : Displaying rows 10 to 40 of 116000 rows. Is there anyway to get this count.

    I would use a combination of:
    [JScrollPane.getViewport().getViewRect()|http://java.sun.com/javase/6/docs/api/javax/swing/JViewport.html#getViewRect%28%29]
    and
    [JTable.rowAtPoint()|http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html#rowAtPoint%28java.awt.Point%29]

  • Implementing a graph scrolling using JScrollPane component

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

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

  • Reloading and redisplay images using JScrollPane

    I am using
    Java platform:jdk 1.4.1
    Windows platform: Windows 98se
    Problem:I am making one application in which i need to display images when i get
    it from socket.I had used one JScrollPane over JPanel with scrollbars.But when i get the image i stored it into an Image object.
    such as in my main program
    screen = Toolkit.getDefaultToolkit().getImage ( "screen.jpg" );
    //Draw picture first time it works fine...
    paintPicture(screen);
    paintPicture(Image image)
         {picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
            image = Toolkit.getDefaultToolkit(  ).getImage(image);
    //Is picpnl is unable to display image second time       
          picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
            c.add( picpnl, BorderLayout.CENTER );
            picpnl.setVisible(true);
    from my refresh code:
           if(image!=null)
              image.flush();
           Runtime rt = Runtime.getRuntime();
           rt.runFinalization();
           rt.gc();
           image = null;
    //is this 2nd time image not properly stored in variable image
           image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
           paintPicture(image);
    //go to paintPicture second time doesn't work
    class ImageComponent extends JComponent {
      Image image;
      Dimension size;
      public ImageComponent(Image image) {
        this.image = image;
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 0);
        try {
          mt.waitForAll(  );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    The above code works fine for (the first time).But when i try to display a different socket image (the second time) it doesn't work.
    I didn't know what the problem is...
    ---whether the previous image didn't get erased from RAM or
    ---the OS is not aware of the current changed image in variable (image) or the
    ---JScrollPane is unable to redraw it second time.
    How can i display one changed image from the socket onto the JScrollPane? (the second time).
    Also i want to know if we are using one file with the name "screen.jpg" and at runtime if i changed that file with another file with the same name. How can i display that changed file?Is it possible in Java or not.(Is it the limitation of Java).
    I totally get frustated by reading all forums but i didn't get the answer.Please reply me soon with the complete code?
    The complete source code for the problem:
    (SERVER):
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto",    "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
         public remote()
              super( "Remote Desktop" );
    c = getContentPane();
              c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
              btnpnl = new JPanel();
              btnpnl.setLayout( new FlowLayout() );
              button = new JButton[names.length];
              icon = new ImageIcon[iconnames.length];
              Buttonhandler handler = new Buttonhandler();
              for( int i=0; i<names.length; ++i )
    icon[i] = new ImageIcon( iconnames[i] );
                   button[i] = new JButton( names, icon[i] );
                   button[i].addActionListener(handler);
    btnpnl.add(button[i]);
              c.add( btnpnl, BorderLayout.NORTH );
              //Adding Label1
              label1 = new JLabel("LABEL1");
              c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
              //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
              c.add( picpnl, BorderLayout.CENTER );
              //setResizable(false);
              setSize( 808, 640 );
              show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
              public void actionPerformed( ActionEvent e )
    try{
                   if( e.getActionCommand() == "looks" )
    try
                   label1.setText( Integer.toString( change ) );
              UIManager.setLookAndFeel( looks[change++].getClassName() );
                        SwingUtilities.updateComponentTreeUI(remote.this);
                   if(change==3)
                        change=0;
    catch (Exception ex)
    ex.printStackTrace();
                   if( e.getActionCommand() == "connect" )
                        label1.setText( "connect" );
    runServer();
                   if( e.getActionCommand() == "refresh" )
                        label1.setText( "refresh" );
                        ous.writeObject("refresh");
                        ous.flush();
                        recieveFile();
                   if( e.getActionCommand() == "auto" )
                        label1.setText( "auto" );
                        ous.writeObject("auto");
                        button[4].setText("stop");
                        ous.flush();
                        setButton(false,false,false,false,true,false);
                   auto();
                   if( e.getActionCommand() == "stop" )
                        ous.writeObject("stop");
                        ous.flush();
                        button[4].setText("auto");
                        setButton(true,true,true,true,true,true);
                   autocontrol=false;
              catch(Exception ef)
                   ef.getMessage();
         public void auto()
              while(autocontrol)
    recieveFile();
         public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
              button[0].setEnabled(b1);
              button[1].setEnabled(b2);
              button[2].setEnabled(b3);
              button[3].setEnabled(b4);
              button[4].setEnabled(b5);
              button[5].setEnabled(b6);
         public void recieveFile()
         int flag = 0;
              try{
                   while(flag<=2){
                   Object recieved = ins.readObject();
                   System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
                                       flag++;
    break;
                   case 1:
    fileName = (String) recieved;
    file = new File(fileName);
                                  System.out.println("fileName received");
                                  flag++;
    break;
                   case 2:
                   if (file.exists())
                        file.delete();
                   byte[] b = (byte[])recieved;
                   FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
                             image.flush();
                                                                Runtime rt = Runtime.getRuntime();
                   rt.runFinalization();
                   rt.gc();
                   image = null;
              Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );          
                        paintPicture(image);
    break;
              catch(Exception e)
                   e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
         public void runServer()
         try{
                   server = new ServerSocket(port);
                   client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
                   System.out.println("connection received from" + client.getInetAddress().getHostName());
                   ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
                   ins = new ObjectInputStream( client.getInputStream() );
                   System.out.println("get i/o streams");
              catch(Exception e)
                   e.printStackTrace();
         public static void main(String[] args)
         remote app = new remote();
         app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    CLIENT code:
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;     
    public Client()
         super("Client");
         Container c = getContentPane();
         ButtonHandler handler = new ButtonHandler();
         c.setLayout( new FlowLayout() );
         label1 = new JLabel("");
         button1 = new JButton("connect");
         c.add(label1);
         c.add(button1);
         button1.addActionListener(handler);
         setSize(300,300);
         show();
    class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         if(e.getActionCommand()=="connect")
                   runClient();
    public void runClient()
         try{     
              server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
              ous = new ObjectOutputStream(server.getOutputStream());
         ous.flush();
              ins = new ObjectInputStream(server.getInputStream());
              System.out.println("get i/o streams");
                   file = new File("screen.jpg");
              listencommands();
         }catch(Exception e)
              e.getMessage();
    public void listencommands()
         try
              while(true){
              Object message = ins.readObject();
         if(message.equals("refresh"))
                   screenshot();
                   sendFile(file);
         if(message.equals("auto"))
                   autocontrol=true;
                   while(autocontrol)
                        screenshot();
                        sendFile(file);
    if(message.equals("stop"))
                   autocontrol = false;
         catch(Exception e)
              e.printStackTrace();
    public void sendFile( File file ) throws IOException
         try{     
              System.out.println("Ready to send file");
              ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
              ous.writeObject("screen.jpg");
              ous.flush();
    System.out.println("fileName send");
              FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
              int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
              System.out.println("Declared array");               
                        //ous.write(size);
                        //ous.flush();
              ous.writeObject(array);
    ous.flush();
              System.out.println("image send");
              catch (Exception e)
                   System.out.println(e.getMessage());
    public void screenshot()
    try
         //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();     
         BufferedImage image = robot.createScreenCapture(rectangle);
         File file;
    //Save the screenshot as a jpg
         file = new File("screen.jpg");
         ImageIO.write(image, "jpg", file);
    catch (Exception e)
         System.out.println(e.getMessage());
    public static void main( String args[] )
              Client app = new Client();
    app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    Steps to run code:
    if everything goes fine:
    1.Run the server.
    2.Run the client.
    3.Press connect button on server.
    4.Press connect on client.
    5.You get a Message box "Connected".
    6.Press refresh button on Server.
    7.You get the first image.
    8.Press refresh button on Server.
    9.You are not going to get anything but the same image.....this is where the problem begins to display that second changed image screenshot.

    /* (SERVER): */
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto", "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
    public remote()
    super( "Remote Desktop" );
    c = getContentPane();
    c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
    btnpnl = new JPanel();
    btnpnl.setLayout( new FlowLayout() );
    button = new JButton[names.length];
    icon = new ImageIcon[iconnames.length];
    Buttonhandler handler = new Buttonhandler();
    for( int i=0; i<names.length; ++i )
    icon = new ImageIcon( iconnames );
    button = new JButton( names, icon );
    button.addActionListener(handler);
    btnpnl.add(button);
    c.add( btnpnl, BorderLayout.NORTH );
    //Adding Label1
    label1 = new JLabel("LABEL1");
    c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
    picpnl.setLayout(new BorderLayout());
    //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
    c.add( picpnl, BorderLayout.CENTER );
    //setResizable(false);
    setSize( 808, 640 );
    show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
    public void actionPerformed( ActionEvent e )
    try{
    if( e.getActionCommand() == "looks" )
    try
    label1.setText( Integer.toString( change ) );
    UIManager.setLookAndFeel( looks[change++].getClassName() );
    SwingUtilities.updateComponentTreeUI(remote.this);
    if(change==3)
    change=0;
    catch (Exception ex)
    ex.printStackTrace();
    if( e.getActionCommand() == "connect" )
    label1.setText( "connect" );
    runServer();
    if( e.getActionCommand() == "refresh" )
    label1.setText( "refresh" );
    ous.writeObject("refresh");
    ous.flush();
    recieveFile();
    if( e.getActionCommand() == "auto" )
    label1.setText( "auto" );
    ous.writeObject("auto");
    button[4].setText("stop");
    ous.flush();
    setButton(false,false,false,false,true,false);
    auto();
    if( e.getActionCommand() == "stop" )
    ous.writeObject("stop");
    ous.flush();
    button[4].setText("auto");
    setButton(true,true,true,true,true,true);
    autocontrol=false;
    catch(Exception ef)
    ef.getMessage();
    public void auto()
    while(autocontrol)
    recieveFile();
    public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
    button[0].setEnabled(b1);
    button[1].setEnabled(b2);
    button[2].setEnabled(b3);
    button[3].setEnabled(b4);
    button[4].setEnabled(b5);
    button[5].setEnabled(b6);
    public void recieveFile()
    int flag = 0;
    try{
    while(flag><=2){
    Object recieved = ins.readObject();
    System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
    flag++;
    break;
    case 1:
    fileName = (String) recieved;
    file = new File(fileName);
    System.out.println("fileName received");
    flag++;
    break;
    case 2:
    if (file.exists())
    file.delete();
    byte[] b = (byte[])recieved;
    FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
    image.flush();
    Runtime rt = Runtime.getRuntime();
    rt.runFinalization();
    rt.gc();
    image = null;
    Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
    paintPicture(image);
    break;
    catch(Exception e)
    e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
    g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    public void runServer()
    try{
    server = new ServerSocket(port);
    client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
    System.out.println("connection received from" + client.getInetAddress().getHostName());
    ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
    ins = new ObjectInputStream( client.getInputStream() );
    System.out.println("get i/o streams");
    catch(Exception e)
    e.printStackTrace();
    public static void main(String[] args)
    remote app = new remote();
    app.addWindowListener(
    new WindowAdapter(){
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    /* End Server */
    /*CLIENT code: */
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;
    public Client()
    super("Client");
    Container c = getContentPane();
    ButtonHandler handler = new ButtonHandler();
    c.setLayout( new FlowLayout() );
    label1 = new JLabel("");
    button1 = new JButton("connect");
    c.add(label1);
    c.add(button1);
    button1.addActionListener(handler);
    setSize(300,300);
    show();
    class ButtonHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand()=="connect")
    runClient();
    public void runClient()
    try{
    server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
    ous = new ObjectOutputStream(server.getOutputStream());
    ous.flush();
    ins = new ObjectInputStream(server.getInputStream());
    System.out.println("get i/o streams");
    file = new File("screen.jpg");
    listencommands();
    }catch(Exception e)
    e.getMessage();
    public void listencommands()
    try
    while(true){
    Object message = ins.readObject();
    if(message.equals("refresh"))
    screenshot();
    sendFile(file);
    if(message.equals("auto"))
    autocontrol=true;
    while(autocontrol)
    screenshot();
    sendFile(file);
    if(message.equals("stop"))
    autocontrol = false;
    catch(Exception e)
    e.printStackTrace();
    public void sendFile( File file ) throws IOException
    try{
    System.out.println("Ready to send file");
    ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
    ous.writeObject("screen.jpg");
    ous.flush();
    System.out.println("fileName send");
    FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
    int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
    System.out.println("Declared array");
    //ous.write(size);
    //ous.flush();
    ous.writeObject(array);
    ous.flush();
    System.out.println("image send");
    catch (Exception e)
    System.out.println(e.getMessage());
    public void screenshot()
    try
    //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(rectangle);
    File file;
    //Save the screenshot as a jpg
    file = new File("screen.jpg");
    ImageIO.write(image, "jpg", file);
    catch (Exception e)
    System.out.println(e.getMessage());
    public static void main( String args[] )
    Client app = new Client();
    app.addWindowListener(
    new WindowAdapter(){
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    }

  • 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(); }
    }

  • JScrollPane: Can the Vertical Scroll Bar go on the left?

    Hope you can help,
    Im using a JScrollPane within another one, i.e, I have a component inside a JScrollPane, and one of its components is a JScrollPane. This is fine and dandy, but the internal scrolled component gets pretty tall and wide, so people end up using the OUTER horizontal scroll bar to scroll to the INNER vertical scrollbar to scroll DOWN the inner component.
    What would be really nice would be to have the INNER scrolled component to have its scroll bar on the LEFT to save the above hassle.
    Is this possible with JScrolledPane?

    In JScrollPane (jdk1.3)
    public void setComponentOrientation(ComponentOrientation co)
    Sets the orientation for the vertical and horizontal scrollbars as determined by the ComponentOrientation argument.
    Parameters:
    co - one of the following values:
    java.awt.ComponentOrientation.LEFT_TO_RIGHT
    java.awt.ComponentOrientation.RIGHT_TO_LEFT
    java.awt.ComponentOrientation.UNKNOWN

  • JScrollPane  - scroll bar not visible

    I'm writing a graphical chat application where the user presses buttons to insert images into their message. The buttons reside in a JPanel with a GridLayout. As i have more buttons than can be physically seen on the screen I'm trying to use a JScrollPane encapsulated in the JPanel so that the user can scroll down the button list to select appropriate symbols. The problem i'm having is that the scroll bars do not appear so the user can only use symbols which are visible. Here is the code for what i'm trying to acheive.
    buttonPanel.setLayout(new GridLayout(9,3));
    buttonPanel.add(Button1);
    buttonPanel.add(Button2);
    buttonPanel.add(Button3);
    buttonPanel.add(Button4);
    .....etc to around Button100
    buttonHolder.add(new JScrollPane());
    buttonHolder.setPreferredSize(new Dimension(400,400));
    buttonHolder.setMaximumSize(new Dimension(400,400));I think I'm missing something from the add JScrollPane bit but I'm not sure what exactly!
    PLEASE HELP - this is for my third year dissertation and is the last bit I need to do before it is finished.

    First, you need to add your panel to the JScrollPane object. Then you add the JScrollPane object to the frame, not the panel itself.
    As for setting the scrollbars of the JScrollPane, you could try setVerticalScrollbarPolicy() and setHorzontalScrollbarPolicy().

  • Can't resize JScrollPane

    I put a JTable in a JScrollPane using
    new JScrollPane(table);
    I can't change the Dimension of the JScrollPane and if the table is greater than the Panel it is cuted even if I scroll max ...
    Any Help is welcomed

    if changing size of the scrollpane does not work and the reason is not the layout you use you could try to put the scrollpane on a panel with Gridlayout(1,1) and resize the panel.

  • 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()!

  • Resizing variable size panel with JScrollPane

    I have a JPanel which contains four radio buttons. Selecting each of them opens another panel which are of different sizes.
    These panels open in the same parent panel below the radio button panel.
    However these panels contain large no of components. i.e. the final size of the main panel varies depeding on which button is selected.
    I am using a JScrollPane to view them properly.
    However, I am facing problem while resizing the main panel. If I mention the preferred size of the JScrollPane, the main panel on maximizing, shows this scrollpane with the size mentioned and does not get maximized as the parent panel.
    If I don't mention the scrollpane size, resizing the main panel don't show the scrollbars.
    what is the correct way to implement a JScrollpane in this case?
    Also can anyone tell me what is the exact deifference between setSize() and setPreferredSize()?

    i think you are looking for this if i got it right.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import javax.swing.WindowConstants;
    public class TestVariablePanelSize extends javax.swing.JPanel
        private JPanel buttonPanel;
        private JRadioButton jRadioButton3;
        private JRadioButton jRadioButton4;
        private JLabel jLabel3;
        private JPanel displayPanel2;
        private JLabel jLabel2;
        private JLabel jLabel1;
        private JPanel jPanel1;
        private ButtonGroup buttonGroup1;
        private JScrollPane jScrollPane1;
        private JToggleButton jToggleButton1;
        private JComboBox jComboBox1;
        private JPanel topPanel;
        private JPanel displayPanel;
        private JPanel parentPanel;
        private JRadioButton jRadioButton2;
        private JRadioButton jRadioButton1;
        JFrame container;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.getContentPane().add(new TestVariablePanelSize(frame));
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public TestVariablePanelSize(JFrame frame)
            super();
            container = frame;
            initGUI();
        private void initGUI()
            try
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                System.out.println("screenSize" + screenSize);
                container.setMaximumSize(screenSize);
                final ErrorReportImportPanel errorReportPanel = new ErrorReportImportPanel();
                BorderLayout thisLayout = new BorderLayout();
                container.setLayout(thisLayout);
                container.setPreferredSize(new java.awt.Dimension(655, 365));
                container.setFocusable(false);
                // START >> jScrollPane1
                // START >>
                buttonGroup1 = new ButtonGroup();
                // END << buttonGroup1
                jScrollPane1 = new JScrollPane();
                container.add(jScrollPane1, BorderLayout.NORTH);
                jScrollPane1.setPreferredSize(new java.awt.Dimension(602, 285));
                // START >> parentPanel
                parentPanel = new JPanel();
                jScrollPane1.setViewportView(parentPanel);
                GridBagLayout parentPanelLayout = new GridBagLayout();
                parentPanelLayout.columnWeights = new double[]{0.1};
                parentPanelLayout.columnWidths = new int[]{7};
                parentPanelLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0};
                parentPanelLayout.rowHeights = new int[]{33, 23, 186, 26};
                parentPanel.setLayout(parentPanelLayout);
                // parentPanel.setPreferredSize(new java.awt.Dimension(652, 371));
                // START >> topPanel
                topPanel = new JPanel();
                parentPanel.add(topPanel, new GridBagConstraints(
                    0,
                    0,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jComboBox1
                ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[]{"Item One", "Item Two"});
                jComboBox1 = new JComboBox();
                topPanel.add(jComboBox1);
                jComboBox1.setModel(jComboBox1Model);
                jComboBox1.setPreferredSize(new java.awt.Dimension(75, 20));
                // END << jComboBox1
                // END << topPanel
                // START >> buttonPanel
                buttonPanel = new JPanel();
                parentPanel.add(buttonPanel, new GridBagConstraints(
                    0,
                    1,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jRadioButton1
                jRadioButton1 = new JRadioButton();
                buttonPanel.add(jRadioButton1);
                jRadioButton1.setText("jRadioButton1");
                jRadioButton1.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel.setVisible(true);
                        // displayPanel2.setVisible(false);
                        // parentPanel.remove(displayPanel2);
                // END << jRadioButton1
                // START >> jRadioButton2
                jRadioButton2 = new JRadioButton();
                buttonPanel.add(jRadioButton2);
                jRadioButton2.setText("jRadioButton2");
                jRadioButton2.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel2.setVisible(true);
                        displayPanel.setVisible(false);
                        parentPanel.remove(displayPanel2);
                // END << jRadioButton2
                // START >> jRadioButton3
                jRadioButton3 = new JRadioButton();
                buttonPanel.add(jRadioButton3);
                jRadioButton3.setText("jRadioButton3");
                // END << jRadioButton3
                // START >> jRadioButton4
                jRadioButton4 = new JRadioButton();
                buttonPanel.add(jRadioButton4);
                jRadioButton4.setText("jRadioButton4");
                // END << jRadioButton4
                // END << buttonPanel
                buttonGroup1.add(jRadioButton1);
                buttonGroup1.add(jRadioButton2);
                buttonGroup1.add(jRadioButton3);
                buttonGroup1.add(jRadioButton4);
                // START >> displayPanel
                displayPanel = new JPanel();
                parentPanel.add(displayPanel, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel.setVisible(false);
                // START >> jLabel2
                jLabel2 = new JLabel();
                displayPanel.add(jLabel2);
                jLabel2.setText("displayPanel");
                jLabel2.setPreferredSize(new java.awt.Dimension(462, 152));
                jLabel2.setOpaque(true);
                jLabel2.setBackground(new java.awt.Color(128, 128, 255));
                jLabel2.setVisible(false);
                // END << jLabel2
                // END << displayPanel
                // START >> displayPanel2
                displayPanel2 = new JPanel();
                parentPanel.add(displayPanel2, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel2.setVisible(false);
                // START >> jLabel3
                jLabel3 = new JLabel();
                displayPanel2.add(jLabel3);
                jLabel3.setText("displayPanel2");
                jLabel3.setOpaque(true);
                jLabel3.setBackground(new java.awt.Color(0, 128, 192));
                jLabel3.setPreferredSize(new java.awt.Dimension(460, 171));
                // END << jLabel3
                // END << displayPanel2
                // START >> jToggleButton1
                jToggleButton1 = new JToggleButton();
                parentPanel.add(jToggleButton1, new GridBagConstraints(
                    0,
                    3,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.WEST,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                jToggleButton1.setText("jToggleButton1");
                // END << jToggleButton1
                // START >> jPanel1
                jPanel1 = new JPanel();
                parentPanel.add(jPanel1, new GridBagConstraints(
                    0,
                    4,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jLabel1
                jLabel1 = new JLabel();
                jPanel1.add(jLabel1);
                jLabel1.setText("Another Panel");
                jLabel1.setPreferredSize(new java.awt.Dimension(469, 87));
                jLabel1.setBackground(new java.awt.Color(0, 128, 0));
                jLabel1.setForeground(new java.awt.Color(0, 0, 0));
                jLabel1.setOpaque(true);
                // END << jLabel1
                // END << jPanel1
                // END << parentPanel
                // END << jScrollPane1
            catch (Exception e)
                e.printStackTrace();
    }

  • JScrollPane + Component sizes before display

    I was recently presented with a minor quandry.
    I have a JPanel which needs to occupy a minimum fixed amount of real estate on my application's GUI, call it 'checkbox_jpanel'. The problem is that as the user operates the application, more and more checkboxes will be added to it. This works fine until I reach the size limit of the JPanel.
    The obvious solution seemed to be to use a JScrollPane, and simply tuck the checkbox_jpanel inside of it. That way, I could dynamically resize the JPanel, and the JScrollPane could take care of displaying it.
    Simple, until I realized that there's no good way to ask a layout manager how much space it had planned to let a given component take up, including buffer pixels. I can't even ask the component itself because, having not yet been drawn, it doesn't know how big it is either.
    Currently, I'm able to get this strategy to work by guessing - eyeballing the number of pixels + space - each new checkbox takes up for the height * the number of items, and the width is based on the largest constant + (constant-intended-to-represent-average-character-width*letters in text portion of checkbox) among the set of checkboxes. I use that width and height to set the preferredSize of the JPanel i'm actually adding to.
    I wince when I look at that code.
    The comment above it says "This really needs to be done correctly."
    How could I do this 'correctly' ?
    The only thing I've been able to come up with is almost as ugly; make the checkbox_jpanel some insanely large size that will always encompass EVERYTHING, insuring that the checkboxes will be drawn, force/wait for the redraw, and then recalculate the width/height, and reset the panel to the desired (correct) width and height. I don't know if I could get this done without a bit of flickering, and really, everything about it screams 'non-optimal solution'.
    Any thoughts?

    Just an idea: the sizes become calculated when the components become visible OR when the application frame is packed... perhaps you could use a call to pack(), then do your job, then finally show your frame ?

  • JScrollPane- Scrolling makes the contents of the Pane garbled

    I have a JTextPane inserted into a JScrollPane and the JSrcollPane is Inserted into the bottom part of the JSplitPane..
      private JTextPane ResultTextPane = new JTextPane();
      ResultScrollPane.getViewport().add(ResultTextPane, BorderLayout.CENTER)
      ResultSplitPane.add(ResultScrollPane, JSplitPane.BOTTOM);Now, When i try scrolling the scrollpane, the text is garbled. (A part of text seems be to dragged when the scroll bar is moved..).If i resize the window, the text is displayed fine and if I start scrolling, the text gets garbled again..
    I am not sure what the problem is? Am I suppose to use a scrollinglistener(AdjustChangeListener) and repaint the contents of the textpane or is it suppose to be happen automatically.

    The easiest way to use a JScrollPane is:
    JScrollPane scrollPane = new JScrollPane( textPane );
    If you need to reset the component in the scrollPane then you would use:
    scrollPane.getViewport().setView( textPane );
    Dont use the add(..) method of the viewport.

  • Jscrollpane dosen't work....

    hi,
    i m using a jscrollpane with a jeditorpane.when i use only jeditorpane to see a html page everything is ok.but when i add jscrollpane to the jeditorpane i cannot see the html page and even the scrollpane.my code is as follows...
    JEditorPane jEditorPane1 = new JEditorPane();
    JScrollPane editorScrollPane = new JScrollPane(jEditorPane1,
              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    editorScrollPane.setPreferredSize(new Dimension(450,500));
    editorScrollPane.setMinimumSize(new Dimension(200,200));
    //panel3.add(jEditorPane1);
    //panel3.add(editorScrollPane);
    this.getContentPane().add(jEditorPane1, null);
    this.getContentPane().add(editorScrollPane,null);
    jEditorPane1.setEditable(false);
    jEditorPane1.setEditorKit(new HTMLEditorKit());
    jEditorPane1.setContentType("text/html");
    try {
         jEditorPane1.setText(inputLine);
    } catch(Exception exp) {
         exp.printStackTrace(System.out);
    here inputline is an html string read from a cgiscript.
    any help would be highly appreciated..
    anurag.

    You cant just add both components like you did here - they will overlay each other
    this.getContentPane().add(jEditorPane1, null);
    this.getContentPane().add(editorScrollPane,null);
    You need to do it this way
    editorScrollPane.setViewPortView(jEditorPane1);
    this.getContentPane().add(editorScrollPane,null);
    then it should work

  • JTable without JScrollPane behavior crippled

    I want column width of JTable t1 goes parallel with the width resizing on
    JTable t2. If tables are put in JScrollPanes, this has no problem. But if I put
    those tables in simpler container, which is JPanel in this case, t2 shows a
    funny behavior -- with user's mouse operation on t2 column, their width
    never changes but t1 column width changes properly. Could I have
    succeeded in communicating the funniness with these sentences?
    Please try this code and give cause and solution if you could:
    import java.awt.*;
    import java.beans.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class TableColumnWidthResize{
      JFrame frame;
      JTable t1, t2;
      TableColumnModel tcm1, tcm2;
      Enumeration columns1, columns2;
      String[] t1h = {"Road", "Length", "City"};
      String[][] t1c
       = {{"NW2", "800", "Dora"},
         {"Iban", "600", "Weiho"},
         {"ENE2", "500","Porso"}};
      String[] t2h = {"Flower", "Curse", "Priest"};
      String[][] t2c
        = {{"Fang", "7.00", "EggChar"},
          {"Shaoma", "5.00", "ScaCra"},
          {"Jiao", "4.00", "PorCabb"}};
      public TableColumnWidthResize(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container con = frame.getContentPane();
        con.setLayout(new GridLayout(2, 1));
        t1 = new JTable(t1c, t1h); //target table -- 'resized from t2'
        t2 = new JTable(t2c, t2h); //source table -- 'initiate resize'
        t1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        t2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        /* you can compare two methods of table placement*/
        useScrollPane(t1, t2, con); //works fine
    //    nouseScrollPane(t1, t2, con); //resize behavior weird
        frame.pack();
        frame.setVisible(true);
        tcm1 = t1.getColumnModel();
        tcm2 = t2.getColumnModel();
        columns2 = tcm2.getColumns(); // all columns of t2
        TableColumnListener tcl = new TableColumnListener();
        while (columns2.hasMoreElements()){
          TableColumn tc = (TableColumn)(columns2.nextElement());
          tc.addPropertyChangeListener(tcl);
      class TableColumnListener implements PropertyChangeListener{
        // achieve 'interlocking-column-resizing' from t2 to t1
        public void propertyChange(PropertyChangeEvent pce){
          TableColumn tc = (TableColumn)(pce.getSource());
          int i = tc.getModelIndex();
          tcm1.getColumn(i).setPreferredWidth(tc.getWidth());
      void useScrollPane(JTable ta, JTable tb, Container c){
        JScrollPane jsc1 = new JScrollPane(ta);
        ta.setPreferredScrollableViewportSize(new Dimension(225, 50));
        JScrollPane jsc2 = new JScrollPane(tb);
        tb.setPreferredScrollableViewportSize(new Dimension(225, 50));
        c.add(jsc1); c.add(jsc2);
      void nouseScrollPane(JTable ta, JTable tb, Container c){
        JPanel p1 = new JPanel(); JPanel p2 = new JPanel();
        p1.setLayout(new BorderLayout());
        p2.setLayout(new BorderLayout());
        p1.add(ta.getTableHeader(), BorderLayout.PAGE_START);
        p2.add(tb.getTableHeader(), BorderLayout.PAGE_START);
        p1.add(ta, BorderLayout.CENTER);
        p2.add(tb, BorderLayout.CENTER);   
        c.add(p1); c.add(p2);
      public static void main(String[] args){
        new TableColumnWidthResize();
    }

    Hey hiwa,
    I don't see anything mysterious going on. If you think about it, how many components can we resize at run-time/dynamically with a mouse - none, except for the columns in a JTable, Frames and Dialogs. Note the latter two are top level and answer to no-one (except the screen i guess).
    If you have ever implemented a component that can be 'dragged' and manipulated by the mouse, have you ever done so outside, that is, not using a JScrollPane? I doubt it.
    I do not think it has anything to do with mouse precision. Maybe you are just experiencing undefined behaviour, unreliable behaviour. I imagine the Swing team didn't bother themselves with a usage scenario that would yield lesser results for a simple task. Using AUTO_RESIZE_OFF and requesting more room than the Container has to offer may upset that containers LayoutManager i.e. their algorithms may contain code that will shrink child components to fit, or nab space from sibling components.
    Basically, in my experience, how ever long it takes me to realise it, when Swing goes on the blink it is usually a programming error.
    BTW, did my suggestion work ok?
    Sorry if I come across forceful. I'm glad I read and tested your code - the synchronization effect will be very useful.
    Warm regards,
    Darren

Maybe you are looking for

  • Why wont new itunes allow me to search podcasts by date/list form anymore?

    One of the best features of itunes podcasts is that you could search a key term and see all the individual podcasts related to it and then sort by date to select the newer ones.  Now it appears with the new upgrade you can't do that, in fact you cann

  • Calendar colours are different in iPhone than what's on my iCal

    Why is it that the colours that I assign in iCal on my computer is different than the colours I see for the same events on the Calendar in the iPhone? Say, for example, I set an event for MISC for a whole day for today, and make it Red in my iCal - w

  • Accounting doc only generating in VF02

    Hi, When we are raising invoice we are finding for certain cases system is not generating the accounting document automatically once the invoice is saved though G/L account is determined.But when we release these invoices again thru VF02 then account

  • Two Machines One Monitor

    I have a graphic design business, and for a number of complicated reasons, I would like to be able to continue working on my G4 running System 9. I would like to add some additional possibilities and capabilities to my workspace, and the most economi

  • Ok to use Dolby 1/0 mono??

    I have a few captures of analog 8mm mono camcorder tapes. I made a mistake during the transfer process by not using an audio Y-cable between the playback camcorder and my capture box. As a result the captured files only have one channel of audio. I d