Loading a Jscrollpane

Hi!
I maybe stupid in not being able to understand the API, but is there a way of, when loading a JScrollPane class, to be able to go to a paticular point in the viewpane.
E.g. I have a ScrollPane. In the viewpane I have a JPanel, 500 pixels wide by 100 pixels high. When I load it, it always opens at 0,0 (ie at the left side). I'd like to load it at point 250,0 (ie in the middle of it)
Is this possible and if so, how?
Thanks in advance!
Tom

Don't blame you for having trouble understanding the Swing API, it's always difficult to understand something that has been abstracted more than one level. However, try this:
yourJScrollPane.getViewPort().setViewPosition(new Point(250, 0));

Similar Messages

  • Making sense of exception

    Hi there,
    I'm working on a project where I'm trying to save to file all the objects
    contained in a class that extends JPanel and implements Serializable. I attempt the save using the following code:
    FileOutputStream fStream = null;
    ObjectOutputStream stream = null;
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    int result = chooser.showSaveDialog(test.this);
    if(result != JFileChooser.APPROVE_OPTION)return;
    File chosenFile = chooser.getSelectedFile();
    FileOpen = chosenFile.getAbsolutePath();
    try
        fStream = new FileOutputStream(chosenFile);
        stream = new ObjectOutputStream(fStream);
        stream.writeObject(docPanel);
        stream.close();
        fStream.close();
    catch(Exception ex)
        ex.printStackTrace();
        try{stream.close();fStream.close();}catch(IOException ioe){}
        JOptionPane.showMessageDialog(test.this, "Error: " + ex.toString(),
            "Warning", JOptionPane.WARNING_MESSAGE);
    [/code
    The save process appears successful since I'm able to open the file and look at it. However, immediately after the save I get the following error at run-time:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at javax.swing.plaf.basic.BasicScrollPaneUI.paint(Unknown Source)
            at javax.swing.plaf.ComponentUI.update(Unknown Source)
            at javax.swing.JComponent.paintComponent(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JComponent.paintChildren(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JComponent.paintChildren(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JComponent.paintChildren(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JViewport.paint(Unknown Source)
            at javax.swing.JComponent.paintChildren(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source)
            at javax.swing.JComponent.paintDoubleBuffered(Unknown Source)
            at javax.swing.JComponent._paintImmediately(Unknown Source)
            at javax.swing.JComponent.paintImmediately(Unknown Source)
            at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
            at
    javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
    n Source)
            at java.awt.event.InvocationEvent.dispatch(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown
    Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
    Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at javax.swing.plaf.basic.BasicScrollPaneUI.paint(Unknown Source)
            at javax.swing.plaf.ComponentUI.update(Unknown Source)
            at javax.swing.JComponent.paintComponent(Unknown Source)
            at javax.swing.JComponent.paint(Unknown Source)
            at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source)
            at javax.swing.JComponent.paintDoubleBuffered(Unknown Source)
            at javax.swing.JComponent._paintImmediately(Unknown Source)
            at javax.swing.JComponent.paintImmediately(Unknown Source)
            at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
            at
    javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
    n Source)
            at java.awt.event.InvocationEvent.dispatch(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown
    Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
    Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)
    There's no reference to any code that I've written in my project, so how am
    I suppose to know where to go to fix the problem?
    The only thing I understand is somewhere there's a NullPointerException.
    But from where does it originate?
    Alan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi there,
    I believe you're right on the money. But damned if I know how to fix it! My project is not that complicated. My main class that extends JFrame declares an instance of JScrollPane at the top, then loads the JScrollPane in an actionPerformed method like so:
    public class test extends JFrame implements ActionListener
      JScrollPane sp2 = new JScrollPane();
      DocumentPanel docPanel = null;
      JMenuItem New = new JMenuItem("New");
      public void actionPerformed(ActionEvent e)
         if(e.getSource() == New)
            Thread newThread = new Thread()
                public void run()
                   //Display a new DocumentPanel
                   docPanel = new DocumentPanel();
                   sp2.getViewport().add(docPanel);
                   container.add(sp2,BorderLayout.CENTER);
                   container.validate();
           newThread.start();
    }docPanel is an object I created that extends JPanel and contains many other objects.
    In the same actionPerformed() method is the code for saving the docPanel from the earlier post. So, any further ideas as to how to prevent the NullPointerException I've been getting with the JScrollPane?
    Alan

  • Loading an image in a JScrollPane

    Hello I have a little problem with an image in a JscrollPane.
    I load my image well, but when it appears in the scroll pane, the vertical and horizontal bars doesn't appear. I have to resize my window with the mouse, and then I can see them.
    Who knows why it happens? What I have to do to see them after loading the image? I tried repaint() and nothing...
    Thanks !!!

    How are you adding your image to the scroll pane? Don't forget that if you have a custom component which renders the image (as opposed to just using a JLabel to render it), you'll want to set its preferred size to match that of the image.

  • 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]);

  • Loading an image into an Applet from a JAR file

    Hello everyone, hopefully a simple question for someone to help me with!
    Im trying to load some images into an applet, currently it uses the JApplet.getImage(url) method just before registering with a media tracker, which works but for the sake of efficiency I would prefer the images all to be contained in the jar file as oppossed to being loaded individually from the server.
    Say I have a class in a package eg, 'com.mydomain.myapplet.class.bin' and an images contained in the file structure 'com.mydomain.myapplet.images.img.gif' how do I load it (and waiting for it to be loaded before preceeding?
    I've seen lots of info of the web for this but much of it is very old (pre 2000) and im sure things have changed a little since then.
    Thanks for any help!

    I don't touch applets, so I can't help you there, but here's some Friday Fun: tracking image loading.
    import java.awt.*;
    import java.awt.image.*;
    import java.beans.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.imageio.event.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class ImageLoader extends SwingWorker<BufferedImage, Void> {
        private URL url;
        private JLabel target;
        private IIOReadProgressAdapter listener = new IIOReadProgressAdapter() {
            @Override public void imageProgress(ImageReader source, float percentageDone) {
                setProgress((int)percentageDone);
            @Override public void imageComplete(ImageReader source) {
                setProgress(100);
        public ImageLoader(URL url, JLabel target) {
            this.url = url;
            this.target = target;
        @Override protected BufferedImage doInBackground() throws IOException {
            ImageInputStream input = ImageIO.createImageInputStream(url.openStream());
            try {
                ImageReader reader = ImageIO.getImageReaders(input).next();
                reader.addIIOReadProgressListener(listener);
                reader.setInput(input);
                return reader.read(0);
            } finally {
                input.close();
        @Override protected void done() {
            try {
                target.setIcon(new ImageIcon(get()));
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        //demo
        public static void main(String[] args) throws IOException {
            final URL url = new URL("http://blogs.sun.com/jag/resource/JagHeadshot.jpg");
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch(url);
        static void launch(URL url) {
            JLabel imageLabel = new JLabel();
            final JProgressBar progress = new JProgressBar();
            progress.setBorderPainted(true);
            progress.setStringPainted(true);
            JScrollPane scroller = new JScrollPane(imageLabel);
            scroller.setPreferredSize(new Dimension(800,600));
            JPanel content = new JPanel(new BorderLayout());
            content.add(scroller, BorderLayout.CENTER);
            content.add(progress, BorderLayout.SOUTH);
            JFrame f = new JFrame("ImageLoader");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(content);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            ImageLoader loader = new ImageLoader(url, imageLabel);
            loader.addPropertyChangeListener( new PropertyChangeListener() {
                 public  void propertyChange(PropertyChangeEvent evt) {
                     if ("progress".equals(evt.getPropertyName())) {
                         progress.setValue((Integer)evt.getNewValue());
                         System.out.println(evt.getNewValue());
                     } else if ("state".equals(evt.getPropertyName())) {
                         if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                             progress.setIndeterminate(true);
            loader.execute();
    abstract class IIOReadProgressAdapter implements IIOReadProgressListener {
        @Override public void imageComplete(ImageReader source) {}
        @Override public void imageProgress(ImageReader source, float percentageDone) {}
        @Override public void imageStarted(ImageReader source, int imageIndex) {}
        @Override public void readAborted(ImageReader source) {}
        @Override public void sequenceComplete(ImageReader source) {}
        @Override public void sequenceStarted(ImageReader source, int minIndex) {}
        @Override public void thumbnailComplete(ImageReader source) {}
        @Override public void thumbnailProgress(ImageReader source, float percentageDone) {}
        @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {}
    }

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • JScrollPane is no longer opaque! Please help.

    I have recently upgraded from Java 1.2.1 to 1.3.1 and switched operating systems from win 98 to win 2000.
    Since doing so I have run an application I have been working on only to find it has slightly changed visually, I don't know what has caused it!
    Basically, I have a JTextArea held within a JScrollPane. The textarea is supposed to be opaque when the application loads, which is still fine, but now even though the textarea is transparent, you can't see the background. Instead all you can see is a large gray block within the limits of the scrollpane. I have tried switching the scrollpane to opaque, but unfortunately this does nothing - the gray stuff is still there.
    I have included the problem code below, please note the code worked fine before, and the only issue here is that I arent getting the true transparency from these components that I desire:
    notes = new JTextArea("Hi");
    scrollPanel = new JScrollPane(notes);
         scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         notes.setPreferredSize(new Dimension(250, 150));
                 notes.setEditable(false);
                 notes.setLineWrap(true);
                 notes.setWrapStyleWord(true);
                 notes.setFont(fontSmall);
                 notes.setOpaque(false);
         notes.addFocusListener(this);
              gbConstraints1.gridx = 0;
              gbConstraints1.gridy = 1;
              gbConstraints1.gridwidth = 2;
              gbConstraints1.gridheight = 1;
              gbConstraints1.ipadx = 1;
              gbConstraints1.ipady = 1;
              gbConstraints1.insets = new Insets(2,2,60,2);
              gbConstraints1.fill = GridBagConstraints.BOTH;
         gbLayout.setConstraints(scrollPanel, gbConstraints1);
    infoHidPane.add(scrollPanel);The line of code 'notes.setOpaque(false);' used to do all the work correctly but this is no longer the case. HELP.
    Thank you for your time. Any comments or suggestions are greatly appreciated.

    Hi!
    I have the same problem. Here is something from the jdk 1.3.1 docs:
    A common operation to want to do is to set the background color that will be used if the main viewport view is smaller than the viewport, or is not opaque. This can be accomplished by setting the background color of the viewport, via scrollPane.getViewport().setBackground(). The reason for setting the color of the viewport and not the scrollpane is that by default JViewport is opaque which, among other things, means it will completely fill in its background using its background color. Therefore when JScrollPane draws its background the viewport will usually draw over it.
    You see that the Viewport is opaque by default. Probably, this is what needs to be changed. If you do have a solution do let me know too.
    Regards,

  • Divide JscrollPane into 2 picure viewer with scroll bar

    Hello to all, help me, i must divide a JScrollPane into 2 sub-windows in witch putting 2 different images.
    The image that i put at left is loaded by a JFileChooser.
    This is the code, my problem is into load_file() function.
    Help me, thanks a lot.
    Escuse me for my bad english.
    package Crypto;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    import java.io.*;
    public class Crypto extends JFrame implements ActionListener {
    private BufferedImage sorgente = null;
    private BufferedImage shares = null;
    private BufferedImage somma = null;
    private JMenuBar mb;
    private JMenu menu1;
    private JMenu menu2;
    private JMenu menu3;
    private JButton go;
    private JButton set_n;
    private JButton set_k;
    private JButton op;
    private JButton schemi;
    private JMenuItem item_01;
    private JMenuItem item_02;
    private JMenuItem item_03;
    private JMenu item_04;
    private JMenuItem item_04_a;
    private JMenuItem item_04_b;
    private JMenuItem item_05;
    private JMenuItem item_06;
    private JMenuItem item_07;
    private JMenuItem item_08;
    private BorderLayout layout = new BorderLayout();
    private JToolBar tb = new JToolBar();
    private int k = 2;
    private int n = 4;
    private String formato = "PNG";
    private File original;
    private File sovra_imp;
    private Schema curr;
    private ImageIcon ii = new ImageIcon();
    private JScrollPane JSPanel;
    private ScrollablePicture picture;
    public Crypto() {
    this.getContentPane().setLayout(layout);
    this.getContentPane().add(BorderLayout.NORTH,tb);
    JSPanel = new JScrollPane();
    //JSPanel.setSize(150, 250);
    this.getContentPane().add(BorderLayout.WEST, JSPanel);
    mb = new JMenuBar();
    mb.setAutoscrolls(true);
    setJMenuBar(mb);
    menu1= new JMenu("File");
    mb.add(menu1);
    item_01 = new JMenuItem("Apri file ...");
    menu1.add(item_01);
    item_02 = new JMenuItem("Quit ...");
    menu1.add(item_02);
    menu2= new JMenu("Impostazioni");
    mb.add(menu2);
    item_03 = new JMenuItem("Formato salvataggio shares");
    menu2.add(item_03);
    item_05 = new JMenuItem("Modifica numero partecipanti");
    menu2.add(item_05);
    item_06 = new JMenuItem("Imposta grado di visibilit�");
    menu2.add(item_06);
    item_04 = new JMenu("Schemi");
    item_04_a = new JMenuItem ("Schema corrente");
    item_04.add (item_04_a);
    item_04_b = new JMenuItem("Modifica schema corrente");
    item_04.add (item_04_b);
    menu2.add(item_04);
    menu3= new JMenu("Help");
    mb.add(menu3);
    item_07 = new JMenuItem("Guida");
    menu3.add(item_07);
    item_08 = new JMenuItem("About");
    menu3.add(item_08);
    op = new JButton ("Apri file ");
    op.addActionListener(this);
    tb.add(op);
    go = new JButton("Crea shares");
    go.addActionListener(this);
    tb.add(go);
    set_k = new JButton("Modifica visibilit� shares");
    set_k.addActionListener(this);
    tb.add(set_k);
    set_n = new JButton("Modifica n. partecipanti");
    set_n.addActionListener(this);
    tb.add(set_n);
    schemi = new JButton("Modifica schema corrente");
    schemi.addActionListener(this);
    tb.add(schemi);
    item_01.addActionListener(this);
    item_02.addActionListener(this);
    item_03.addActionListener(this);
    item_04_a.addActionListener(this);
    item_04_b.addActionListener(this);
    item_05.addActionListener(this);
    item_06.addActionListener(this);
    item_07.addActionListener(this);
    item_08.addActionListener(this);
    curr = Schema.carica_schema ("2-2-b-w");
    this.setBounds(150, 150, 800, 500);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setTitle("Crypto magic");
    this.setVisible(true);
    public void actionPerformed(java.awt.event.ActionEvent ae) {
    Object source = ae.getSource();
    Class sourceClass = source.getClass();
    if (sourceClass.getName().equals("javax.swing.JMenuItem")){
         JMenuItem ch = (JMenuItem) source;
    if (ch == item_01){
    load_file();
    }else if (ch == item_02){
    close_frame();
    }else if (ch ==item_03){
    scegli_formato();
    }else if (ch == item_04_a){
    schema_corrente();
    }else if (ch == item_04_b){
    cambia_schema();
    }else if (ch == item_05){
    set_n();
    }else if (ch == item_06){
    set_k();
    }else if (ch == item_07){
    guida();
    }else about();
    if (sourceClass.getName().equals("javax.swing.JButton")){
    JButton jb = (JButton) source;
    if (jb == go){
    crea_shares();
    }else if (jb == set_n){
    set_n();
    }else if (jb == op){
    load_file();
    }else if (jb == set_k){
    set_k();
    public void load_file() {
    JFileChooser fc = new JFileChooser();
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(new ImageFilter());
    int retval = fc.showOpenDialog(this);
    try{
    if (retval == JFileChooser.APPROVE_OPTION){
    original = fc.getSelectedFile();
    //String nome = original.getName();
    sorgente = ImageIO.read (original);
    ii.setImage(sorgente);
    picture = new ScrollablePicture(ii, 1);
    JSPanel = new JScrollPane(picture, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    this.getContentPane().add(BorderLayout.WEST, JSPanel);
    this.repaint();
    }catch (Exception e){}
    void close_frame(){
    System.exit(0);
    void scegli_formato(){
    Impostazioni i = new Impostazioni(0);
    void set_n(){
    Impostazioni i = new Impostazioni(2);
    void set_k (){
    Impostazioni i = new Impostazioni(1);
    Schema schema_corrente(){
    return curr;
    void cambia_schema(){}
    void guida(){
    void about(){
    void crea_shares(){
    public class Impostazioni extends JFrame implements ChangeListener{
    JTabbedPane panel = new JTabbedPane();
    Impostazioni(int i){
    FSS c1 = new FSS();
    SET_K c2 = new SET_K();
    SET_N c3 = new SET_N();
    panel.add("Formato shares", c1);
    panel.add("Modifica K", c2);
    panel.add("Modifica N", c3);
    panel.addChangeListener(this);
    if ( i == 0){
    panel.setSelectedComponent(c1);
    }else if ( i == 1){
    panel.setSelectedComponent(c2);
    }else if (i == 2){
    panel.setSelectedComponent(c3);
    getContentPane().add(panel);
    this.setResizable(false);
    this.setBounds(200, 200, 500, 300);
    this.setTitle("Impostazioni");
    this.setVisible(true);
    public void stateChanged(ChangeEvent e) {
    int pos = panel.getSelectedIndex();
    String title = panel.getTitleAt(pos);
    setTitle(title);
    public class FSS extends JPanel implements ActionListener{
    private JComboBox cb;
    private JLabel et;
    JLabel ico;
    Icon i1 = new ImageIcon("C:/forte/sampledir/Crypto/JPGIcon.jpg");
    Icon i2 = new ImageIcon("C:/forte/sampledir/Crypto/PNGIcon.jpg");
    FSS(){
    this.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 30));
    int i;
    String item []= {"JPG", "PNG"};
    for (i = 0; i < 1; i++)
    if (item == formato) break;
    String msg = "\n\n\n\n\nIl formato attualmente in uso � "+formato+"\n\n";
    et = new JLabel(msg);
    add(et);
    JLabel et2 = new JLabel ("Modidica il formato di salvataggio delle shares ");
    if (formato =="JPG"){
    ico = new JLabel(i1);
    }else {ico = new JLabel(i2);}
    add (ico);
    add (et2);
    cb = new JComboBox(item);
    cb.setSelectedIndex(i);
    cb.addActionListener(this);
    add(cb);
    public void actionPerformed(java.awt.event.ActionEvent ae) {
    JComboBox cb = (JComboBox)ae.getSource();
    String selectedItem = (String)cb.getSelectedItem();
    int ind = cb.getSelectedIndex();
    formato = selectedItem;
    et.setText("Il formato attualmente in uso � "+selectedItem);
    if (formato == "PNG"){
    ico.setIcon(i2);
    }else{
    ico.setIcon(i1);
    public class SET_K extends JPanel implements ActionListener{
    private JLabel et3;
    SET_K(){
    this.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 40));
    String msg = "Il valore attuale di k � "+k+"\n\n";
    et3 = new JLabel(msg);
    et3.setFont(new Font("Tim", Font.BOLD, 16 ));
    add (et3);
    JButton but2 = new JButton ("Modifica K");
    add (but2);
    but2.addActionListener(this);
    public void actionPerformed(java.awt.event.ActionEvent ae) {
    Object source = ae.getSource();
    int value;
    Class sourceClass = source.getClass();
    if (sourceClass.getName().equals("javax.swing.JButton")){
    Kappa kappa= new Kappa();
    value = kappa.get_K();
    if ((value > n) ||(value < 2)){
    JOptionPane err = new JOptionPane();
    String err_msg ="Errore, il valore di K deve essere un intero compreso tra 2 e " +n;
    err.showMessageDialog(null,err_msg , "Errore", JOptionPane.ERROR_MESSAGE);
    this.setVisible(false);
    }else{
    k = value;
    JOptionPane ok_ = new JOptionPane();
    ok_.showMessageDialog(null, "Modifica effettuata con successo. ");
    et3.setText("Il valore attuale di K � " +value);
    this.setVisible(false);
    public class SET_N extends JPanel implements ActionListener{
    private JLabel et4;
    SET_N(){
    this.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 40));
    String msg = "Il valore attuale di n � "+n+"\n\n";
    et4 = new JLabel(msg);
    et4.setFont(new Font("Tim", Font.BOLD, 16 ));
    add (et4);
    JButton but3 = new JButton ("Modifica N");
    add (but3);
    but3.addActionListener(this);
    public void actionPerformed(java.awt.event.ActionEvent ae) {
    Object source = ae.getSource();
    int value;
    Class sourceClass = source.getClass();
    if (sourceClass.getName().equals("javax.swing.JButton")){
    Kappa kappa= new Kappa();
    value = kappa.get_K();
    if (value < k){
    JOptionPane err = new JOptionPane();
    String err_msg ="Errore, il valore di N deve essere un intero superiore o uguale a " +k;
    err.showMessageDialog(null,err_msg , "Errore", JOptionPane.ERROR_MESSAGE);
    this.setVisible(false);
    }else{
    n = value;
    JOptionPane ok_ = new JOptionPane();
    ok_.showMessageDialog(null, "Modifica effettuata con successo. ");
    et4.setText("Il valore attuale di N � " +value);
    this.setVisible(false);
    public int salva_schema(Schema s){
    String nome = s.get_name();
    nome = nome + ".ctm";
    try{
    FileOutputStream fos = new FileOutputStream (nome);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(s);
    oos.close();
    return 1;
    catch (Exception ioe){
    return -1;
    public Schema leggi_schema (String nome){
    try{
    nome = nome + ".ctm";
    FileInputStream fis = new FileInputStream (nome);
    ObjectInputStream ois = new ObjectInputStream(fis);
    Schema salvato = (Schema)(ois.readObject());
    ois.close();
    return salvato;
    catch (Exception ioe){
    return null;
    public static void main(String args[]){
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) { }
    JFrame f = new Crypto();
    f.setVisible(true);
    package Crypto;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    /* ScrollablePicture.java is used by ScrollDemo.java. */
    public class ScrollablePicture extends JLabel
    implements Scrollable,
    MouseMotionListener {
    private int maxUnitIncrement = 1;
    private boolean missingPicture = false;
    public ScrollablePicture(ImageIcon i, int m) {
    super(i);
    if (i == null) {
    missingPicture = true;
    setText("No picture found.");
    setHorizontalAlignment(CENTER);
    setOpaque(true);
    setBackground(Color.white);
    maxUnitIncrement = m;
    //Let the user scroll by dragging to outside the window.
    setAutoscrolls(true); //enable synthetic drag events
    addMouseMotionListener(this); //handle mouse drags
    //Methods required by the MouseMotionListener interface:
    public void mouseMoved(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) {
    //The user is dragging us, so scroll!
    Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
    scrollRectToVisible(r);
    public Dimension getPreferredSize() {
    if (missingPicture) {
    return new Dimension(320, 480);
    } else {
    return super.getPreferredSize();
    public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
    public int getScrollableUnitIncrement(Rectangle visibleRect,
    int orientation,
    int direction) {
    //Get the current position.
    int currentPosition = 0;
    if (orientation == SwingConstants.HORIZONTAL) {
    currentPosition = visibleRect.x;
    } else {
    currentPosition = visibleRect.y;
    //Return the number of pixels between currentPosition
    //and the nearest tick mark in the indicated direction.
    if (direction < 0) {
    int newPosition = currentPosition -
    (currentPosition / maxUnitIncrement)
    * maxUnitIncrement;
    return (newPosition == 0) ? maxUnitIncrement : newPosition;
    } else {
    return ((currentPosition / maxUnitIncrement) + 1)
    * maxUnitIncrement
    - currentPosition;
    public int getScrollableBlockIncrement(Rectangle visibleRect,
    int orientation,
    int direction) {
    if (orientation == SwingConstants.HORIZONTAL) {
    return visibleRect.width - maxUnitIncrement;
    } else {
    return visibleRect.height - maxUnitIncrement;
    public boolean getScrollableTracksViewportWidth() {
    return false;
    public boolean getScrollableTracksViewportHeight() {
    return false;
    public void setMaxUnitIncrement(int pixels) {
    maxUnitIncrement = pixels;

    Instead of "new ImageFilter()", use this file filter:
    public static javax.swing.filechooser.FileFilter SOLOMENTE_JPG_GIF_PNG=
    new javax.swing.filechooser.FileFilter(){
    public String getDescription(){
    return "jpg, gif, o png";
    public boolean accept(java.io.File file){
    String n= file.getName();
    return n.endsWith(".jpg") || n.endsWith(".gif") || n.endsWith(".png");
    public void load_file() {
    JFileChooser fc = new JFileChooser();
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(SOLOMENTE_JPG_GIF_PNG); // <-- NUEVO
    int retval = fc.showOpenDialog(this);
    try{
    if (retval == JFileChooser.APPROVE_OPTION){
    original = fc.getSelectedFile();
    //String nome = original.getName();
    sorgente = ImageIO.read(original);
    ii.setImage(sorgente);
    picture = new ScrollablePicture(ii, 1);
    JSPanel = new JScrollPane(picture, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    this.getContentPane().add(BorderLayout.WEST, JSPanel);
    this.repaint();
    }catch (Exception e){}

  • Loading XML Document from JFileChooser

    My initial version of this app I hardcoded the XML filename. Now, I would like to load an xml file via a JFileChooser. The problem I'm having is that I create the DOM Document in the constructor because of dependencies on the JTree. Well, I don't call showDialog until the "open" action is called which is further into the program. By then it's too late. Here is the code. I extracted some unecessary code for reading purposes.
    public class DomGui extends JPanel implements DomGuiConstants, ActionListener
        private JScrollPane treeView;
        private String xmlFilename;
        private Document document;
        private JFileChooser fileChooser;
        private ExtensionFilter fileFilter;
        private static JFrame frame;
        private static JTree jtree;
        public DomGui() throws Exception
            frame = new JFrame(DOM_VIEWER);
            fileChooser = new JFileChooser();
            fileFilter = new ExtensionFilter(XML_EXTENSION, XML_DESCRIPTION);
            // Create the Document
            //xmlFilename = "W:/RoseModel/ImplementationView/seng/ewcs/clwc/Simulation/Utilities/Xml/DomViewer/TVschedule.xml";
            try
                CreateDomDocument createDomDocument = new CreateDomDocument(xmlFilename);
                document = createDomDocument.getDocument();
            catch (FileNotFoundException fnfe)
                System.out.println(fnfe);
                System.exit(1);
            // Create a Tree Model
            DomTreeModel model = new DomTreeModel(document);
            // Create a renderer
            DomTreeCellRenderer  treeCellRenderer = new DomTreeCellRenderer();
            // Create the JTree
            jtree = new JTree(model);
            // Create an Editor
            DomTreeCellEditor treeCellEditor = new DomTreeCellEditor(jtree);
            // Build left-side view
            // an empty tree and put it a JScrollPane so users can see
            // its contents as it gets large
            treeView = new JScrollPane(jtree);
            treeView.getViewport().add(jtree);
            treeView.setPreferredSize(new Dimension( leftWidth, windowHeight ));
            // Create a JSplitPane to hold the left side JTree
            // and the right side JEditorPane
            // Build split-pane view
            splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                                       treeView,
                                                       htmlView );
            splitPane.setContinuousLayout( true );
            splitPane.setDividerLocation( leftWidth );
            splitPane.setPreferredSize(new Dimension
                                                        ( windowWidth + 10, windowHeight+10 ));
            // Add GUI components
            this.setLayout(new BorderLayout());
            this.add("Center", splitPane );
        public static void makeFrame()
            int FRAME_WIDTH = 670;
            int FRAME_HEIGHT = 600;
            // Set up the tree, the views, and display it all
            try
                final DomGui guiPanel = new DomGui();
                frame.getContentPane().add("Center", guiPanel );
            catch (Throwable throwable)
                throwable.printStackTrace();
                System.exit(1);
        public void actionPerformed(ActionEvent actionEvent)
            String actionCommand = actionEvent.getActionCommand();
            System.out.println("Action: " + actionCommand);
            if (actionCommand.equalsIgnoreCase("Quit"))
                System.exit(0);
            else if (actionCommand.equalsIgnoreCase("Open"))
                showDialog("Open XML File",
                                 "Open",
                                 "Open the file",
                                 'o',
                                 null);
        // end actionPerformed
        public File showDialog (String dialogTitle,
                                            String approveButtonText,
                                            String approveButtonToolTip,
                                            char approveButtonMnemonic,
                                            File file)
            fileChooser.setDialogTitle(dialogTitle);
            fileChooser.setApproveButtonText(approveButtonText);
            fileChooser.setApproveButtonToolTipText(approveButtonToolTip);
            fileChooser.setApproveButtonMnemonic(approveButtonMnemonic);
            fileChooser.setFileSelectionMode(fileChooser.FILES_ONLY);
            fileChooser.rescanCurrentDirectory();
            fileChooser.setSelectedFile(file);
            fileChooser.addChoosableFileFilter(fileFilter);
            fileChooser.setFileFilter(fileFilter);
            int result = fileChooser.showDialog(this, null);
            System.out.println("Result is: " +result);
            if (result == fileChooser.APPROVE_OPTION)
                System.out.println("I'm Here 1");
                System.out.println("File selected: " + fileChooser.getSelectedFile());
                xmlFilename = fileChooser.getSelectedFile().toString();
                return fileChooser.getSelectedFile();
            else
                System.out.println("I'm Here 2");
                return null;
        // end showDialog
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    In your actionPerformed() method, shouldn't you do something with the File returned by showDialog()? For instance:
            else if (actionCommand.equalsIgnoreCase("Open"))
                xmlFilename = showDialog("Open XML File",
                                 "Open",
                                "Open the file",
                                'o',
                                 null).getName();
            }Because it seems that, for now at least, you're choosing a file and then just kinda throwing it away...

  • Zoom Issues with JScrollPane

    Hello all,
    I have ran into an issue with zoom functionality on a JScrollPane.
    Here is the situation (code to follow):
    I have a JFrame with a JDesktopPane as the contentpane. Then I have a JScrollPane with a JPanel inside. On this JPanel are three rectangles. When they are clicked on, they will open up a JInternalFrame with their name (rect1, rect2, or rect3) as the title bar. Rect3 is positioned (2000,2000).
    I have attached a mousewheel listener to the JPanel so I can zoom in and out.
    I have also attached a mouse listener so I can detect the mouse clicks for the rectangles. I also do a transformation on the point so I can be use it during clicks while the panel is zoomed.
    All of this works fantastic. The only issue I am having is that when the JScrollPane scroll bars change, I cannot select any of the rectangles.
    I will give a step by step reproduction to be used with the code:
    1.) Upon loading you will see two rectangles. Click the far right one. You'll see a window appear. Good. Move it to the far right side.
    2.) Zoom in with your mouse wheel (push it towards you) until you cannot zoom anymore (May have to get focus back on the panel). You should see three rectangles. Click on the newly shown rectangle. Another window, titled rect3 should appear. Close both windows.
    3.) This is where things get alittle tricky. Sometimes it works as intended, other times it doesn't. But do something to this affect: Scroll to the right so that only the third rectangle is showing. Try to click on it. If a window does not appear - that is the problem. But if a window does appear, close it out and try to click on the 3rd rect again. Most times, it will not display another window for me. I have to zoom out one step and back in. Then the window will appear.
    After playing around with it for awhile, I first thought it may be a focus issue...I've put some code in the internal window listeners so the JPanel/JScrollPane can grab the focus upon window closing, but it still does not work. So, either the AffineTransform and/or point conversion could be the problem with the scroll bars? It only happens when the scroll bar has been moved. What affect would this have on the AffineTransform and/or point conversion?
    Any help would be great.
    Here is the code, it consists of two files:
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    public class InternalFrameAffineTransformIssue
         public static void main ( String[] args )
              JFrame frame = new JFrame("AffineTransform Scroll Issue");
              frame.setLayout(null);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JDesktopPane desktop = new JDesktopPane();
              frame.setContentPane(desktop);
              MyJPanel panel = new MyJPanel(frame);
              JScrollPane myScrollPane = new JScrollPane(panel);
              panel.setScrollPane(myScrollPane);
              myScrollPane.setLocation(0, 0);
              myScrollPane.setSize(new Dimension(800, 800));
              myScrollPane.getVerticalScrollBar().setUnitIncrement(50);
              myScrollPane.getHorizontalScrollBar().setUnitIncrement(50);
              myScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
              frame.getContentPane().add(myScrollPane);
              frame.setBounds(0, 100, 900, 900);
              frame.setVisible(true);
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.NoninvertibleTransformException;
    import java.awt.geom.Point2D;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.InternalFrameAdapter;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    public class MyJPanel extends JPanel implements MouseWheelListener
              double zoom = 1;
              Rectangle rect1 = new Rectangle(50, 50, 20, 20);
              Rectangle rect2 = new Rectangle(100, 50, 20, 20);
              Rectangle rect3 = new Rectangle(2000, 2000, 20, 20);
              AffineTransform zoomedAffineTransform;
              JFrame frame;
              JPanel myPanel = this;
              JScrollPane myScrollPane;
              public MyJPanel(JFrame inputFrame)
                   setAutoscrolls(true);
                   addMouseListener(new MouseAdapter(){
                        public void mousePressed ( MouseEvent e )
                             System.out.println("Clicked: " + e.getPoint());
                             AffineTransform affineTransform = zoomedAffineTransform;
                             Point2D transformedPoint = e.getPoint();
                             //Do the transform if it is not null
                             if(affineTransform != null)
                                  try
                                       transformedPoint = affineTransform.inverseTransform(transformedPoint, null);
                                  catch (NoninvertibleTransformException ex)
                                       ex.printStackTrace();
                             System.out.println("Tranformed Point: " + transformedPoint);
                             if(rect1.contains(transformedPoint))
                                  System.out.println("You clicked on rect1.");
                                  createInternalFrame("Rect1");
                             if(rect2.contains(transformedPoint))
                                  System.out.println("You clicked on rect2.");
                                  createInternalFrame("Rect2");
                             if(rect3.contains(transformedPoint))
                                  System.out.println("You clicked on rect3.");
                                  createInternalFrame("Rect3");
                   addMouseWheelListener(this);
                   frame = inputFrame;
                   setPreferredSize(new Dimension(4000, 4000));
                   setLocation(0, 0);
              public void paintComponent ( Graphics g )
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.scale(zoom, zoom);
                   zoomedAffineTransform = g2d.getTransform();
                   g2d.draw(rect1);
                   g2d.draw(rect2);
                   g2d.draw(rect3);
              public void mouseWheelMoved ( MouseWheelEvent e )
                   System.out.println("Mouse wheel is moving.");
                   if(e.getWheelRotation() == 1)
                        zoom -= 0.05;
                        if(zoom <= 0.20)
                             zoom = 0.20;
                   else if(e.getWheelRotation() == -1)
                        zoom += 0.05;
                        if(zoom >= 1)
                             zoom = 1;
                   repaint();
              public void createInternalFrame ( String name )
                   JInternalFrame internalFrame = new JInternalFrame(name, true, true, true, true);
                   internalFrame.setBounds(10, 10, 300, 300);
                   internalFrame.setVisible(true);
                   internalFrame.addInternalFrameListener(new InternalFrameAdapter(){
                        public void internalFrameClosed ( InternalFrameEvent arg0 )
                             //myPanel.grabFocus();
                             myScrollPane.grabFocus();
                        public void internalFrameClosing ( InternalFrameEvent arg0 )
                             //myPanel.grabFocus();
                             myScrollPane.grabFocus();
                   frame.getContentPane().add(internalFrame, 0);
              public void setScrollPane ( JScrollPane myScrollPane )
                   this.myScrollPane = myScrollPane;
         }

    What I'm noticing is your zoomedAffineTransform is changing when you click to close the internal frame. This ends up being passed down the line, thus mucking up your clicks until you do something to reset it (like zoom in and out).
    Clicking on the JInternalFrame appears to add a translate to the g2d transform. This translation is what's throwing everything off. So in the paintComponent where you set the zoomedAffineTransform, you can verify if the transform has a translation before storing the reference:
             if (g2d.getTransform().getTranslateX() == 0.0) {
                zoomedAffineTransform = g2d.getTransform();
             }Edited by: jboeing on Oct 2, 2009 8:23 AM

  • Setting JTextArea text within a JScrollPane

    Hey all. I'm attempting to use the setText() method of JTextArea to set the text of various areas located in various scroll panes. The general procedure I'm following is to initialize a new JTextArea and JScrollPane within an initializeGui function, set the properties of the JTextArea, then add it to the scroll pane using .getViewport().add(). After that, a separate function goes through all my form fields loading them with whatever data type is appropriate, in the case of the text areas I'm trying to use setText() to set a string. However, after using setText() the text area is displaying nothing. Here's some code for example (workerPane is using a layout manager exclusive to the environment I'm working in, but I don't believe it's the problem).
    workerLabel = new JLabel("Customer Address:");
              JScrollPane sp = new JScrollPane();          
              JTextArea ta = new JTextArea();          
              //set ta's properties to whatever is needed
              ta.addKeyListener(new java.awt.event.KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        JTextArea text = (JTextArea)e.getSource();                    
                        String txt = text.getText();                    
                        int nameLength = 240;
                        if ( txt.length() >= nameLength ){
                             text.setText ( txt.substring( 0, nameLength-1 ) );                         
                             Toolkit.getDefaultToolkit().beep();                    
              sp.getViewport().add(ta);          
              workerPane.add("3.1.right.top",workerLabel);
              workerPane.add("3.2.left.center",custAddScrollPane);After each area has been initialized, another function is called to load the data into it. Here are some methods I've tried that haven't worked.
    //basic, but leaves an empty field.
    ta.setText(formProperties[2].getStringValue());
    //this results in two NullPointerException warning windows popping
    ta=(JTextArea)sp.getViewport().getView();
    if(formProperties[2].getStringValue() != null)         ta.setText(formProperties[2].getStringValue());
    sp.getViewport().removeAll();
    sp.getViewport().add(ta);Can anyone point me in the right direction as to how to set my textarea's text?

    I usually use the approach given above. The other option is:
    scrollPane.setViewportView( textArea );

  • JScrollPane scroll bar trouble on rebuild

    I've been working on this for hours (about 4 hours now) without finding the right solution, so maybe someone can help. I searched through a few pages of the forum but didn't see this exact issue. And the tutorial online doesn't help much.
    I have a JPanel in a JScrollPane in a JFrame. The JFrame has it's height reduced if its over a particular size (in the test case, it gets reduced). When it first loads, it's fine. However, if I rebuild the whole JFrame (some event causes the JPanel content to change, and refresh() is called again), the window remains the same size but the vertical scroll bar extends off the bottom of the frame. If I manually resize the frame with the mouse (even by 1 pixel), the scroll bar updates and looks correct again. What is the correct way to do this? Calling revalidate() on the JScrollPane after doing the setSize() doesn't do anything. And why does it work the first time when the JFrame is first built through the Constructor?
    example code:
    public class MyFrame extends JFrame {
        public MyFrame() {
            super();
            refresh();
        private void refresh() {
            JPanel jp = new JPanel();
            jp.setLayout(new SpringLayout());
            // add some stuff to jp
            JScrollPane scrollPane = new JScrollPane(
                JScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
            scrollPane.getViewport().add(jp);
            setContentPane(scrollPane);
            pack();
            if (getHeight() > MAX_HEIGHT) {
                setSize(getWidth(),MAX_HEIGHT);
    }

    When you have changed the content, call getRootPane().validate(); instead of pack(), as in this slightly modified version of your sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyFrame extends JFrame implements ActionListener {
        private static final int MAX_HEIGHT = 100;
        public MyFrame() {
            super();
            refresh(true);
        public static void main(String[] args) {
            MyFrame myFrame = new MyFrame();
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setVisible(true);
        private void refresh(boolean pack) {
            JPanel jp = new JPanel();
            jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
            JButton refreshButton = new JButton("Refresh");
            refreshButton.setActionCommand("refresh");
            refreshButton.addActionListener(this);
            jp.add(refreshButton);
            jp.add(new JLabel("Hello"));
            jp.add(new JLabel("There"));
            jp.add(new JLabel("Why"));
            jp.add(new JLabel("Doesn't"));
            jp.add(new JLabel("Refresh"));
            jp.add(new JLabel("Work"));
            JScrollPane scrollPane = new JScrollPane(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
            scrollPane.getViewport().add(jp);
            setContentPane(scrollPane);
            if (pack) {
                pack();
            else {
                getRootPane().validate();
            if (getHeight() > MAX_HEIGHT) {
                setSize(getWidth(),MAX_HEIGHT);
        public void actionPerformed(ActionEvent ae) {
            refresh(false);
    }

  • How to load data from text.txt fiel and tokenize it into JCombo box???

    Hi Everyone,
    I am new to Java and Netbeans. I am working on the same GUI project and need your Help!!
    I have two queries and since i am new,please if possible explain step by step
    1.) How can I load the contents of data stored in sometext.txt file when i click the JCombo box]?? Also, if i enter a new string not existing in text, it should display a message and add the new entered data into the sometext.txt file.
    2.) How can i input the contents of table.txt file (which has characters seperated by Tab) into a JTable into specific rows and columns??. Again, the txt should add and update the new entered data.
    I dont want to use any databse connection!!
    Explainations with Examples/Attachments will be greatly and truly appreciated
    Please Please Help me ASAP as i have to submit this assignment by next week!!

    hi camickr,
    I tried to load a file into Jtable. I have used random access file method to read a large text file seperated by tabs. When i tried to run the file, i was unable to load the data from the file. i guess i am missing the link between custom table and the default table. Can you please help me?
    The complete code is attached below:.(The reason i am attaching the whole code is ..so that you can check me where i am going wrong, please dont mind!!)
    package javaapplication;
    import java.io.*;
    import java.util.ArrayList;
    import javax.swing.table.AbstractTableModel;
    public class table extends javax.swing.JFrame {
    /** Creates new form table */
    public class FileTableModel extends AbstractTableModel {
    RandomAccessFile raf;
    ArrayList<Long> lineToPos = new ArrayList<Long>();
    int columnCount = -1;
    public FileTableModel(String fileName) {
    try {
    raf = new RandomAccessFile(new File(fileName), "C://temp.txt");
    lineToPos.add(new Long(0));
    String line = null;
    while ((line = raf.readLine()) != null) {
    if (columnCount == -1)
    columnCount = line.split(" ").length;
    lineToPos.add(new Long(raf.getFilePointer()));
    lineToPos.remove(lineToPos.size()-1);
    } catch (Exception e) {
    e.printStackTrace();
    protected void finalize() throws Throwable {
    super.finalize();
    raf.close();
    public int getColumnCount() {
    return columnCount;
    public int getRowCount() {
    return lineToPos.size();
    public Object getValueAt(int rowIndex, int columnIndex) {
    try {
    raf.seek(lineToPos.get(rowIndex).longValue());
    String line = raf.readLine();
    String[] strs = line.split(" ");
    return strs[columnIndex];
    } catch (IOException e) {
    e.printStackTrace();
    return null;
    /** 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.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTable1.setModel(jTable1.getModel());
    jScrollPane1.setViewportView(jTable1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(15, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(14, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new table().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable jTable1;
    // End of variables declaration
    }

  • Resize jtable in jscrollpane

    Hi,
    I have a frame containing a JTable and a panel with buttons. When the window gets resized, I would like that the jtable takes the extra space and that the button panel stays the same. How can I do that? The jtable panel is already the "Center" and both panels stay the same...
    Thanks,
    Marie
    Here's the code:
    package test;
    import javax.swing.*;
    import java.awt.AWTEvent;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class Testframe extends JFrame {
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JPanel tablePanel = new JPanel();
        //Button panel
        private JButton applyTableBt = new JButton("Generate Table");
        private JButton addBt = new JButton("Add");
        private JButton editBt = new JButton("Edit");
        private JButton deleteBt = new JButton("Delete");
        private JButton matchBt = new JButton("Find");
        private JButton saveBt = new JButton("Save to file");
        private JButton loadBt = new JButton("Load from file");
         * Constructor.
         * @param a_parent Frame
        protected Testframe() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
                this.setResizable(true);
                this.setVisible(true);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
         * Initialization of the dialog.
         * @throws Exception
        private void jbInit() throws Exception {
            this.setTitle("Pattern management - CAT");
            Object[][] data = { {"11", "12", "13", "14", "15", "16", "17", "18"},
                              {"21", "22", "23", "24", "25", "26", "27", "28"}
            Object[] names = {"col1", "col2", "col3", "col4", "col5", "col6",
                             "col7", "col8"};
            JTable table = new JTable(data, names);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //table.setColu
            TableColumnModel colModel = table.getColumnModel();
            for (int i = 0; i < table.getColumnCount(); i++) {
                TableColumn column = colModel.getColumn(i);
                column.setPreferredWidth(511);
            JScrollPane scrollPane = new JScrollPane(table);
            tablePanel.add(scrollPane);
            //Layout = vertical box with vertical gap
            buttonPanel.setLayout(new GridLayout(7, 1, 0, 5));
            buttonPanel.add(applyTableBt);
            buttonPanel.add(addBt);
            buttonPanel.add(editBt);
            buttonPanel.add(deleteBt);
            buttonPanel.add(matchBt);
            buttonPanel.add(saveBt);
            buttonPanel.add(loadBt);
            //mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
            this.setContentPane(mainPanel);
         * Overrides this class to call the good method when the dialog is closed.
         * @param a_windowE WindowEvent
        protected void processWindowEvent(WindowEvent a_windowE) {
            //If it is a request to close the window (X)
            if (a_windowE.getID() == WindowEvent.WINDOW_CLOSING) {
                cancel();
            super.processWindowEvent(a_windowE);
         * Closes the dialog.
        private void cancel() {
            dispose();
        private static void createAndDisplayFrame() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            new Testframe();
        public static void main(String[] args) {
            createAndDisplayFrame();
    }

    try changing these lines
    mainPanel.add(tablePanel, BorderLayout.CENTER);
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    this.setContentPane(mainPanel);
    to this
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(mainPanel, BorderLayout.EAST);

  • JList(Vector) inside JScrollPane vanishes!

    Hi all, I have a problem thats driving me crazy, Im really stumped on this one;
    Im trying to update the GUI on a packet sniffer I wrote a while ago,
    I have a GUI class below as part of a larger program, this class containes a JList(Vector) inside a JScrollPane inside a JPanel inside a JFrame, I want this JList to be on the screen all the time, and grow dynamically as new elements are added to the Vector.
    Elements are added via an accessor method addPacket(Capture), you can assume the other classes in my program work fine.
    The problem is, the JFrame periodically goes blank, sometimes the scrollbars are present, sometimes not. After a while (sometimes) the JList reappears, containing the list of packets as it should, but it never lasts very long. Often it will disappear permanently.
    The class below is pretty short and simple, I really hope this is a simple and obvious mistake Ive made that someone can spot.
    Thanks,
    Soothsayer
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.InputStream;
    public class GUI extends JFrame
         Dimension screenResolution = Toolkit.getDefaultToolkit().getScreenSize();
         private InputStream fontStream = this.getClass().getResourceAsStream("console.ttf");
         Font outputFont;
         static final Color FIELD_COLOR = new Color(20, 20, 60);
         static final Color FONT_COLOR = new Color(150, 190, 255);
         private static JPanel superPanel = new JPanel();
         private static Vector<Capture> packetList = new Vector<Capture>(1000, 500);
         private static JList listObject = new JList(packetList);
         private static JScrollPane scrollPane = new JScrollPane(listObject);
         public GUI()
              super("LineLight v2.1 - Edd Burgess");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(50, 10);
              try { outputFont = Font.createFont(Font.TRUETYPE_FONT, fontStream); }
              catch(Exception e) { System.err.println("Error Loading Font:\n" + e); }
              outputFont = outputFont.deriveFont((float)10);
              listObject.setFont(outputFont);
              superPanel.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              superPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
              scrollPane.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane.setWheelScrollingEnabled(true);
              superPanel.add(scrollPane);
              this.add(superPanel);
              this.pack();
         public void addPacket(Capture c)
              this.packetList.add(c);
              this.listObject.setListData(packetList);
              this.superPanel.repaint();
    }

    I'm having basically the same problem, And how is your code different than the example in the tutorial???
    You can also read the tutorial section on "Concurrency".
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    Start your own posting if you need further help.

Maybe you are looking for

  • Hiding Blank column spaces in crystal reports

    Hello, I would like to completely hide a column in crystal reports. I can hide the column details however this leaves a blank space in that column position. Is it possible to hide the blank spaces and rearrange the other columns such that no blank sp

  • How to save a variant when running a transaction (PU19)

    Hello everyone:          PU19 is the tax reporter transaction but when you run it there is no provision to save a variant. User has to select lot of data onb selection screen and they don't want to do this everytime they run the program and instead s

  • Webdynpro for java 怎么实现弹出一个popup window时,使原来的窗口变的不太明显?

    webdynpro for java 怎么实现弹出一个popup window时,使原来的窗口变的不明显,比如变模糊,或者消失都行.不知道怎么实现?

  • Images displayed strangely in Firefox

    So, I have this bizarre issue with firefox.  Some images (but not all) get displayed with very strange colours. For example: And how this image should look: This only occurs in firefox.  I have tried removing the ~/.mozilla directory, to no effect. 

  • Download does not occur?

    I am in the desktop app and I select adobe pdf download and nothing happens. this is my first time and I need to take some pictures and turn it into a pdf file. Can I contact someone to help?