JScrollPane Visibility

Hey,
I'm having some issues with setVisible on JScrollPanes.
Basically I'm writing a little class that's storing settings using java.util.Properties.
These settings are checked on load to see if it should display some certain buttons, and a JScrollPane.
I've also included a JMenu with checkbox items to toggle visibility of these buttons/JScrollPane during runtime.
Now to the problem, when I launch the class with the JScrollPane disabled in configuration I can't seem to make it visible again.
The setVisible(true); line is being run, as I've printlned the object on change. But it's just not appearing on screen.
When the class is run with the JScrollPane enabled in configuration it runs fine, and changes visibility on demand.
Heres a small example snippet:
Properties config = new Properties();
config.load(new FileInputStream("configfile.cfg));
if (config.get("showScroll")!=null) {
    if (config.get("showScroll").equals("0") {
        scrollPane.setVisible(false);
    } else {
        scrollPane.setVisible(true);
} else {
    config.setProperty("showScroll","1");
    scrollPane.setVisible(true);
}Then the toggle button changes setVisible(); between true/false and config.setProperty("showScroll","1/0");.
So basically if at runtime "showScroll" = "0" the scrollPane won't be visible, and the toggle button won't make it visible even though it is changing the state.
If "showScroll" = "1" the scrollPane will be visible, and the toggle button will toggle it between visible and invisible without any hassles.
Sorry if this post is mumbled, 3am here and I'm a bit tired.
Thanks in advance.

Ahh great, thanks heaps.
I came so close as well, I had actually tried repaint() with no luck.
validate(); worked a treat :)

Similar Messages

  • JScrollPane visible part refresh rate problem

    I am writing an application that reads image and displays it in a JScrollPane via JPanel. It also has JSlider to set displayed image focus. The problem is that sometimes when big image is loaded and user changes seen part via scrollbars, the JScollPane refresh takes about 10 sec. The question is: How to make JScrollPane's content refresh/repaint only the part that is visible. The code is:
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    public class Main extends JFrame{
        private BufferedImage image;
        private JScrollPane sPane;
        private ImagePanel iPanel;
        private JSlider slider;
        private Container contentPane;
        public Main() {
            try {
                image = ImageIO.read(new File("c:\\pict\\img.JPG"));
            } catch (IOException ioe){
                ioe.printStackTrace();
                System.exit(1);
            slider = new JSlider(JSlider.HORIZONTAL,1,3,1);
            slider.setMinorTickSpacing(1);
            slider.setMajorTickSpacing(1);
            slider.setSnapToTicks(true);
            slider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    iPanel.setImageFocus(slider.getValue());
                    invalidate();
            iPanel = new ImagePanel(image);
            sPane = new JScrollPane(iPanel,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            contentPane = this.getContentPane();
            contentPane.add(slider,BorderLayout.NORTH);
            contentPane.add(sPane,BorderLayout.CENTER);
            setExtendedState(JFrame.MAXIMIZED_BOTH);
            setDefaultCloseOperation(3);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
    class ImagePanel extends JPanel{
        private Image img;
        private Dimension imageSize;
        public ImagePanel(Image img){
            this.img = img;
            imageSize = new Dimension(img.getWidth(null),img.getHeight(null));
        public void setImage(Image img){
            this.img = img;
        public void setImageFocus(int focus){
            if (this!=null){
                getGraphics().clearRect(0,0,imageSize.width,imageSize.height);
            switch (focus){
                case 1:
                    imageSize = new Dimension(img.getWidth(null),img.getHeight(null));
                    break;
                case 2:
                    imageSize = new Dimension(2*img.getWidth(null),2*img.getHeight(null));
                    break;
                case 3:
                    imageSize = new Dimension(3*img.getWidth(null),3*img.getHeight(null));
                    break;
                default:
                    imageSize = new Dimension(0,0);
            setSize(imageSize);
            setPreferredSize(imageSize);
            repaint();
            ((JScrollPane)getParent().getParent()).revalidate();
        public void paintComponent(Graphics g){
            JScrollPane sp = (JScrollPane)getParent().getParent();
            g.clearRect(sp.getX(),sp.getY(),sp.getWidth(),sp.getHeight());
            g.drawImage(img,0,0,imageSize.width,imageSize.height,null);
    }Thanks,

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • JScrollPane scroll setting first column is not visible?

    Hi All,
    i am using jtable and jscrollpane. in this my first column of 70 pixal width and rest 125 pixal width.set focus is on 1 cell(1 row, 1 column) in table. but due to this scrollbar is slightly on right side whice coz first column not visible.(need to drag for visibility). i am trying to make it visible without dragging.
    how to do this? HELP.
    i tried with tableScroll.scrollRectToVisible(table.getCellRect(0,0,true )); & -1,-1
    but it didnt worked.
    Code is like this..........
    table = new JTable(64,65){
    table.setName("Table");
    ((DefaultTableModel)table.getModel()).setColumnIdentifiers(vectName.getColumnIdentifiers());
              for(int i = 0;i<table.getRowCount();i++) {
                   table.setValueAt((i+1)+"",i,0);
              table.setGridColor(Color.black);
              table.setSelectionBackground(new Color(125,255,144));
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              table.setCellSelectionEnabled(true);          
              table.addKeyListener(listener);
              table.addMouseListener(listener);
              table.getSelectionModel().addListSelectionListener(this);
              table.getColumnModel().addColumnModelListener(this);
              table.getColumnModel().getColumn(0).setResizable(false);
              table.getColumnModel().getColumn(0).setMinWidth(70);
              table.getColumnModel().getColumn(0).setMaxWidth(70);
    JScrollPane tableScroll = new JScrollPane(table);
    Dimension minimumSize = new Dimension(100,25);
    tableScroll.setMinimumSize(minimumSize);          
    add(tableScroll);

    Hi weebib ,
    pls find some working code which shous my problame .
    you can see its coming to column 'B'. but i want it to show from column 'A' .
    sample working code : =
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.util.*;
    public class myTable extends JFrame{
    JTable table;
    JScrollPane jsp;
    JPanel p1;
    int NO_OF_ROWS = 64;
    int NO_OF_COLUMNS = 65;
    Vector vColumnNames ;
    myTable(){
         Container con = getContentPane();
         p1 = new JPanel();
         table = new JTable(NO_OF_ROWS,NO_OF_COLUMNS){
              public boolean isCellEditable(int row, int column) {
                                  if(column == 0){
                                       return false;
                                  else{
                                       return true;
         setTableProperties();
         jsp = new JScrollPane(table);
         p1.add(jsp);
         con.add(p1);
         setSize(400,500);
         show();
         //System.out.println("Hello there");
    public Vector getColumnIdentifiers(){
         vColumnNames = new Vector();
                   for(int i=65;i<129;i++) {
                        vColumnNames.add(new String((char)i+""));// setting the alphabets for the column names //orig
         return vColumnNames ;
    public void setTableProperties(){
         ((DefaultTableModel)table.getModel()).setColumnIdentifiers(getColumnIdentifiers());
         for(int i = 0;i<table.getRowCount();i++) {
                        table.setValueAt((i+1)+"",i,0);// Set the names of the row
         table.setGridColor(Color.black);
         table.setSelectionBackground( Color.RED);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.setCellSelectionEnabled(true);
         table.addMouseListener(new myMouseListener());
         table.addKeyListener(new myKeyListener());
    //     table.getColumnModel().getColumn(0).setPreferredWidth(125);
    //     table.getColumnModel().getColumn(0).setResizable(false);
    //     table.getColumnModel().getColumn(0).setMinWidth(70);
    //     table.getColumnModel().getColumn(0).setMaxWidth(70);
         for(int u =0 ;u<64;u++){
              if(u==0){
                   table.getColumnModel().getColumn(u).setPreferredWidth(70);
              else{
                   table.getColumnModel().getColumn(u).setPreferredWidth(200);
         table.changeSelection(0,1,false,false);
    static public void main(String[] args){
              myTable test = new myTable();
              test.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){System.exit(0);}
    public class myMouseListener extends MouseAdapter{
         public void mousePressed(MouseEvent me){
                   table.repaint();
    public class myKeyListener extends KeyAdapter{
         public void keyPressed(KeyEvent ke){
                   if(table.getSelectedColumn() == 0){
                        ke.consume();
    ================
    pls do reply back if i am doing something wrong.
    == Gavin

  • JScrollPane  - scroll bar not visible

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

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

  • How to know if a scrollbar is been drawn if the JScrollPane is not visible.

    I have a JTabbedPane with one JPanel in each tab. Each of these panels contains one JLabel with a JTextBox on the top and under it the rest is filled with a JScrollPane containing a JTable. I am using a GridBagLayout.
    Now, the requirement is that the JTextBox must have the same length as the content of the JScrollPane; it means that if the JScrollPane has a vertical scroll, the JText has to be shorter on the right side by whatever the scroll width is, but if there's no vertical scroll then the JTextBox must be extended to the top of the right side.
    Now, this that looks so simple is becoming a nightmare...
    The main problem here is that this check to look if the JScrollPane has a scroll or not is done in tabs that are not visible, so i cannot use just a simple isVerticalScrollVisible() because the answer is always NO. I have been trying to catch all the events i could think may help but no luck and sometimes a refresh in one of the tabs produces the JTextField in another tab gets a wrong width.
    One posible approach is the length of the total rows of the JTable, multiply it by the row height and compare it with... with what because the scroll is not visible and the heigh is 0.
    Any ideas? Any one knows how can i know if the the silly scrollbar is visible or not in a non visible tab?
    Thanks in advance.

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

  • JScrollPane (added to a JPanel, which paints) is visible but does nothing

    Hi. I am writing a program that reads data from files and does paiting using the info. The top level window is a JFrame, which is divided into two parts - A Box which contains the buttons through which the user interacts and a JPanel on which the painting is done. I have added the JPanel to a JScrollPane, but have run into problems there. The JScrollPane is visible (both policies always visible) but it does nothing. I understand that when the drawing is fitting, the ScrollPane is not used. But even if I make the window small or draw something that is not visible in the normal are, the JScrollPane doesn't work. In fact, no knob is visible on either of the two scrollbars. I am pasting the relevant code below:
    //import
    public class MainWindow extends JFrame {
        public static void Main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel;   
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
    } I hope this helps you get an idea of what I am trying to do and what the problem might be. Any help would be really appreciated. I have spent hours on this and I have no idea why it doesn't work.
    The actual code is much bigger, so if you need any extra information, please tell me.

    HelloPanel should provide a "public Dimension getPreferredSize()" method.
    With your code you create a simple JPanel and want to draw outside of it, but you never tell the JScrollPane that your HelloPanel is actually bigger than it seems, that's why it does not feel the need to add scroll bars.
    Here's the working code:
    //import
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class MainWindow extends JFrame {
        public static void main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel; 
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            //this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            //buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            //buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                //if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
         public Dimension getPreferredSize()
         return new Dimension(750,750);
    }

  • Getting Visible text - JTextPane in a JScrollPane

    I have a JTextPane wrapped in a JScrollPane. I want to be able to get the text that is visible at any given time. I want JUST the text that is visible, not the entire text of the document.
    The method to use is obviously getText(int offset, int length), which is from JTextComponent.
    I am wondering how I can retrieve the given offset (ie. the position of the very first visible character) and length (ie. the ending position of the last visible character minus the position of the starting character) from either the JScrollPane or the JTextPane.
    I believe that this might be a rather complex problem as I'm qutie certain I am going to have to manually compute a few things by using several different views.
    Any help anyone could offer would be most appreciated.

    Hi camickr
    I got the JScrollPane now thanks.
    Now I'm still confused on how to solve the original problem.
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    public class TestJTextPane extends JTextPane implements ComponentListener{
          public static void main (String args[]){
               JFrame mainFrame = new JFrame();
               mainFrame.setSize(500,300);
               mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               mainFrame.getContentPane().add(new JScrollPane(new TestJTextPane()));
               mainFrame.setVisible(true);
          public TestJTextPane(){
                this.addComponentListener(this);
          private void viewVisibleText(){
               int offSet = 0;
               int length = 0;
               try{
                    JScrollPane scrollPane = (JScrollPane) this.getParent().getParent();
                    System.out.println(scrollPane.getViewport().getVisibleRect());
                    System.out.println(this.viewToModel(scrollPane.getViewport().getVisibleRect().getLocation()));
               catch (Exception e){
                    e.printStackTrace();
         public void componentResized(ComponentEvent arg0) {
              viewVisibleText();
         public void componentMoved(ComponentEvent arg0) {
              viewVisibleText();
         public void componentShown(ComponentEvent arg0) {
         public void componentHidden(ComponentEvent arg0) {
              // TODO Auto-generated method stub
    }If you run this, you will see that the Rectangle for the getVisibleRect() does not changed, and the call to viewToModel will always return 0.
    Can you please point out where I'm going wrong.
    Thanks for the help

  • Determining the visible lines of a JEditorPane within a JScrollPane

    I need to track what lines are visible (the Document line numbers) within the Viewport of a JScrollPane that contains a JEditorPane. Is this achievable?

    That's a tricky one.
    Maybe something like this:
    First get the view coordinate of the top left corner of the view port
    Point p = scrollPane.getViewPort().getViewPosition();Then convert that view location into a model location. The model location will be an index into the document.
    int modelLocation = editorPane.viewToModel( p );Now you just need to count how many lines are before this index location. As I recall there is a main root element for the whole document. The root element is made up of child elements, one for each line. This may be different for HTML but might work for text or rich text.
    Element rootElement = editorPane.getDocument().getRootElements()[0];
    // getElementIndex() will give you the child element index (e.g. line element that is at the given document location).
    int lines = rootElement.getElementIndex( modelLocation );Do the same for the point location that is at the viewport's location plus the viewport's size (i.e. the lower right corner of the viewport).
    There is a LOT of speculation here since I haven't actually put this to a test case. But maybe its enough to point you in a direction that works.
    -Mike

  • JScrollPane: specify viewable area and paint only visible

    Hi, I have an application that I want to make fast updates to the screen and it has a large amount of data to paint, how do i specify the extent of the view to JScrollPane, and how do I get the coordinates of the scrollbars or the viewport to my underlying JPanel.paintComponent() so that I can paint only the visible area in absolute panel coordinates?
    This is not possible by implementing Scrollable or make a custom JViewport , at least in my own experiments. What am I missing here?
    Btw, how do i change the with of the Scrollbars in JScrollPane, they are to thin.

    I havent been able to test the above suggestions yet so I cant tell if it will work.
    The problem is really how to tell JScrollPane how big the scrolling area is.
    I have an amount of data that I want to paint on the screen and the scrollbars should specify what data that I should paint. The problem is how do i communicate this to the JScrollPane? And how to get info back?
    I want to decide myself which data to paint.
    Specifically I must tell the JScrollPane how big area to scroll so that it can adjust the Scrollbars accordingly, and I must get info of what the JScrollPane is pointing to.

  • JScrollPane in a JFrame scrollbars visible but not functional no thumbtabs

    Here is the code that I compiled and run on J2SE v. 1.4.2 (runtime b28). I looked through the various related articles and nothing seems to help with this issue. The scrollbars appear along with the panel but the thumbtabs are not present. Any help would be appreciated.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
      public static void main(String[] args){
        Test rce = new Test();
        JFrame frame = new JFrame("Test Scroll");
        JScrollPane scrollBar = new JScrollPane();
        scrollBar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        Component  rcePage = rce.createComponents();
        scrollBar.getViewport().add(rcePage, null);
        frame.getContentPane().add(scrollBar, null);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setSize(400, 400);
        frame.setVisible(true);
      public Component createComponents() {
        JPanel pan = new JPanel();
        JLabel label = new JLabel("This is a Test!");
        pan.setBorder(BorderFactory.createEmptyBorder(
            0, //top
            0, //left
            0, //bottom
            0) //right
        pan.setLayout(null);
        label.setBounds(100, 100, 80, 20);
        pan.add(label);
        return pan;
    }

    This is a very common mistake. When you put a JPanel in a scrollpane, the scrollpane will use the panel's preferred size to determine if scrolling is needed or not. If the panel is using a LayoutManager this is generally done for you automatically. But in your case you set the layout to null, and then it is your responsibility to make sure that the getPreferredSize() method of the panel returns the correct size.
    One way to fix this in the code you posted would be to override the getPreferredSize() of the panel, like so:
        public Component createComponents() {
            JPanel pan = new JPanel() {
                public Dimension getPreferredSize() {
                    return getSize();
        }Then the scrollbars will appear if you make the frame smaller.
    But what I really suggest is that you use a LayoutManager.

  • JScrollPane: Contents not visible

    I am having trouble using JScrollPane. My situation is this ...
    I have an abstract class (PanelSupport) that extends JPanel and a class (TaskPane) that extends this abstract class. I want to add the class TaskPane to a JScrollPane but when I do this the scroll pane appears empty.
    I previously had the TaskPane being displayed without a scroll pane and it worked a treat but as soon as I introduce the JScollPane and insert the TaskPane into that I see nothing in the scroll pane. Any clues as to why?

    I am having trouble using JScrollPane. My situation
    is this ...
    I have an abstract class (PanelSupport) that extends
    JPanel and a class (TaskPane) that extends this
    abstract class. I want to add the class TaskPane to a
    JScrollPane but when I do this the scroll pane appears
    empty.
    I previously had the TaskPane being displayed without
    a scroll pane and it worked a treat but as soon as I
    introduce the JScollPane and insert the TaskPane into
    that I see nothing in the scroll pane. Any clues as
    to why?Just a stab in the dark but if you are not already doing this, try:
    yourscrollpane.getViewport().add(yourpanel);

  • How to add a JScrollPane in a JPanel

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

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

  • Varying size of JScrollPane

    Hi.
    I hope you can help me figure out what's going on. I have a component that I've written that should display buttons vertically (it's a basis for an OutlookBar styled component).
    The component is based on a JPanel that is put in a JScrollPane and the buttons are added to the JPanel. The JPanel has a VerticalFlowLayout (a custom layout class).
    Now for the problem: Every time I adjust the size of the component so that a scroll bar should appear, the getPreferredSize() method of the JScrollPane returns a width that is lesser than it returns when the scroll bar is not visible! The weird thing is that the difference in the width is exactly the width of the scroll bar... but it doesn't make much sense since the width that is returned when the scroll bar is visible is less than the width that is returned when the scroll bar is not visible (it would make sense to have it the other way around!).
    Since my component needs to keep a consistent width this behavior is extremely annoying! Below you can find the code for the panel (and the needed layout) if you'd like to try this out, any help will be greatly appreciated:
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    * A panel that contains a set of operations that are displayed under a common
    * category name on a <code>OutlookBar</code>.
    * @version Revision:$ Date:$
    public class OutlookBarCategoryPanel extends JPanel
        protected JPanel m_contentPanel = new JPanel( new VerticalFlowLayout( 5 ) );
        private JScrollPane m_contentScrollPane = new JScrollPane( m_contentPanel,
                                                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         * Constructs a new <tt>OutlookBarCategoryPanel</tt> that is initially empty.
        public OutlookBarCategoryPanel()
            super( new BorderLayout() );
            m_contentPanel.setBackground( SystemColor.control );
            super.add( m_contentScrollPane, BorderLayout.CENTER );
         * If the <code>preferredSize</code> has been set to a
         * non-<code>null</code> value just returns it.
         * If the UI delegate's <code>getPreferredSize</code>
         * method returns a non <code>null</code> value then return that;
         * otherwise defer to the component's layout manager.
         * @return the value of the <code>preferredSize</code> property
         * @see #setPreferredSize
         * @see ComponentUI
        public Dimension getPreferredSize()
            Dimension size = super.getPreferredSize();
            if( size.width < m_contentScrollPane.getPreferredSize().width )
                size.width = m_contentScrollPane.getPreferredSize().width;
            return size;
         * Appends the specified component to the end of this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @return    the component argument
        public Component add( Component comp )
            return m_contentPanel.add( comp );
         * Adds the specified component to the end of this container.
         * Also notifies the layout manager to add the component to
         * this container's layout using the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp the component to be added
         * @param     constraints an object expressing
         *                  layout contraints for this component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see       LayoutManager
         * @since     JDK1.1
        public void add( Component comp, Object constraints )
            m_contentPanel.add( comp );
         * Adds the specified component to this container with the specified
         * constraints at the specified index.  Also notifies the layout
         * manager to add the component to the this container's layout using
         * the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param comp the component to be added
         * @param constraints an object expressing layout contraints for this
         * @param index the position in the container's list at which to insert
         * the component; <code>-1</code> means insert at the end
         * component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see #remove
         * @see LayoutManager
        public void add( Component comp, Object constraints, int index )
            m_contentPanel.add( comp, index );
         * Adds the specified component to this container at the given
         * position.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @param     index    the position at which to insert the component,
         *                   or <code>-1</code> to append the component to the end
         * @return    the component <code>comp</code>
         * @see #addImpl
         * @see #remove
         * @see #validate
         * @see #revalidate
        public Component add( Component comp, int index )
            return m_contentPanel.add( comp, index );
         * Adds the specified component to this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * This method is obsolete as of 1.1.  Please use the
         * method <code>add(Component, Object)</code> instead.
         * @see add(Component, Object)
        public Component add( String name, Component comp )
            return m_contentPanel.add( name, comp );
         * Removes the specified button from the panel.  The reference that is sent as
         * a parameter needs to point to the same instance as the button that should actually
         * be removed (in other words, this method will not perform an equal() comparison).
         * @param button    a reference to the button that should be removed.
        public void remove( OutlookBarOperationButton button )
            m_contentPanel.remove( button );
         * Removes all operations that have the specified caption.
         * @param caption   the caption of the operation(s) that should be removed.
        public void removeOperation( String caption )
            Component[] components = m_contentPanel.getComponents();
            for( int i=0; i<components.length; i++ )
                Component component = components;
    if( component != null && component instanceof AbstractButton )
    if( ((AbstractButton)component).getText().equals( caption ) )
    m_contentPanel.remove( i );
    public static void main( String[] args )
    JFrame frame = new JFrame( "OutlookBarCategorButton" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().setLayout( new BorderLayout() );
    OutlookBarCategoryPanel obcp = new OutlookBarCategoryPanel();
    obcp.add( new OutlookBarOperationButton( "foo", new ImageIcon( "images/History24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "bar", new ImageIcon( "images/Help24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "foobar", new ImageIcon( "images/Cut24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "index 2", new ImageIcon( "images/isl_faninn.png" ) ), 2 );
    frame.getContentPane().add( obcp, BorderLayout.WEST );
    frame.pack();
    frame.show();
    And here is the code for the VerticalFlowLayout class:
    import java.awt.*;
    * A layout manager that works like the default layout manager in swing
    * (FlowLayout) except that it arranges its components vertically instead
    * of horizontally.
    * @version $Revision: 1.1 $ $Date: 2003/03/11 13:37:38 $
    public class VerticalFlowLayout implements LayoutManager
        private int m_vgap;
         * Creates a new instance of the class with an initial vertical gap of 0
         * pixels.
        public VerticalFlowLayout()
            this( 0 );
         * Creates a new instance of the class with an initial vertical gap of
         * the specified number of pixels.
         * @param vgap  the number of pixels to use as a gap between
         *              components
        public VerticalFlowLayout( int vgap )
            m_vgap = vgap;
         * Lays out the container in the specified panel.
         * @param theParent the component which needs to be laid out
        public void layoutContainer( Container theParent )
            Insets insets = theParent.getInsets();
            int w = theParent.getSize().width - insets.left - insets.right;
            int numComponents = theParent.getComponentCount();
            if( numComponents == 0 )
                return;
            int y = insets.top;
            int x = insets.left;
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent(i);
                if( c.isVisible() )
                    Dimension d = c.getPreferredSize();
                    c.setBounds( x, y, w, d.height );
                    y += d.height + m_vgap;
         * Calculates the minimum size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #preferredLayoutSize
        public Dimension minimumLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getMinimumSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;
         * If the layout manager uses a per-component string,
         * adds the component <code>comp</code> to the layout,
         * associating it
         * with the string specified by <code>name</code>.
         * @param name the string to be associated with the component
         * @param comp the component to be added
        public void addLayoutComponent( String name, Component comp )
         * Removes the specified component from the layout.
         * @param comp the component to be removed
        public void removeLayoutComponent( Component comp )
         * Calculates the preferred size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #minimumLayoutSize
        public Dimension preferredLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getPreferredSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;

    You can use calligraphy/ art brush strokes, can you not? Some of them come with AI and you can find quite a few on ze interweb. You could even create your own, if need be.
    Mylenium

  • How to find out if JTable's selected row is visible?

    Hello there,
    Given:
    a JTable is inserted into a JScrollPane and the number of rows in the table is greater than the vieport size.
    A random row within the table gets programmatically selected.
    How to find out if the selected row is visible in a JTable visible area?
    Your help will be greatly appreciated.
    Tim

    That will make the row visible, but not answer whether it was visible
    in the first place. Try something like:
    public boolean isRowVisible( JTable table, int row ) {
        Rectangle rect = table.getBounds();
        int rowHeight = table.getRowHeight();
        int viewHeight = table.getParent().getHeight();
        int max = rect.y - viewHeight + 1;
        int rowPos = - rowHeight * row;
        return ( rect.y >= rowPos && rowPos > max );
    }assuming all rows have the same height.
    : jay

  • JScrollPane not scrolling to the end of JTable

    Hello,
    I put a table in a scroll pane, and add the scroll pane to a panel. The problem is the scroll pane does not scroll to the end of the table, it always lets me view only the first 37 rows of the table, regardless of how many rows the table actually has. Basically, the scroll pane thinks the table has exactly the same height, no matter how many lines it has. Why is this happening?
    The code is something like
    model = new SearchResultTableModel(false, null, null);
    table = new ResultTable(model);
    scrollPane = new JScrollPane(table);
    mainBox.add(scrollPane);
    If this is important, the table is a bit more complicated, I subclass JTable, use a custom TableModel, several types of cell renderers / editors, so maybe this is why it behaves so strange. How could I tell the scroll pane the table is actually larger?
    Thank you very much, any ideas are highly appreciated,
    Regards from Romania,
    Adi

    Hi,
    fireTableDataChanged() is the easiest way to do it, but also that one, that forces JTable to rerender all visible cells, regardless the fact, that they are already displayed and would not need rerendering - if you add a row - for example row 7 - do fireTableRowsInserted(7,7); instead - so JTable will only render this single row if it is visible in the viewport. If you add a couple of rows, for example row 7 to 227, do fireTableRowsInserted(7,227); - always fire only the correct notifications accordingly to the changes you make, in order to keep the performance of JTable high.
    greetings Marsian

Maybe you are looking for

  • Using SharePoint Open with File Exployer - works with Windows 7 but not with 8.1

    I am using a SharePoint site. There is an option to open the site in File Explorer [Open in Explorer] that I can use with Windows 7 computers with no problems.  However, when I try to use in Windows 8.1, I receive an error message telling me to add t

  • History for a CLOB field in APEX

    Hello! We have implemented a History for our APEX application using triggers. Everything is ok with it, but there are some CLOB fields which cannot be handled in this way (cannot compare the value of the bind variables :new and :old, because one of t

  • Arabic name displaying in JLabel using html tags

    If i execute the following code the value of the variable product_name as latin characters it's displaying correctely. If i use arabic characters it's adding white spaces import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swin

  • IPod Classic 160GB looping restore.

    After moving my iTunes library to another disk and confirming that files were fine, I plugged in my iPod to sync and charge it, and it said that it was in recovery mode and required a restore. No problem I thought. Had a little time, so clicked resto

  • ORA-01031 + NODEINFO=NO_VALUE

    Hello everyone, I finaly got the DBCA working. 1) I installed the latest JAVA that I could find on the sun.java.com website (j2sdk_1_4_2_05...). Now, the commands which java and java -version return appropriate values. 2) I made an entry in my /etc/h